<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class Borrow_model extends CI_Model {

    function __construct() {
        parent::__construct();
    }

    //标的参数信息
    function arrays($key) {
        $data = array(
            'borrow_type' => array("7" => "担保标", "2" => "抵押标", "1" => "信用标","3" => "净值标","4" => "流转标","5" => "秒标"),
            'borrow_guarantee' => array("1" => "担保机构", "2" => "抵(质)押物", "3" => "安全保障"),
            'bTypeGrt' => array('1' => '3', '2' => '2', '7' => '1'),
            'borrow_type_search' => array("1" => "信用标", "2" => "抵押标", "7" => "担保标","3" => "净值标","4" => "流转标","5" => "秒标"),
            'borrow_type_img' => array("1" => "信", "2" => "抵","3"=>"净","4"=>"流","5" => "秒", "7" => "担",),
            'borrow_type1' => array("1" => "信用", "2" => "抵押", "3" => "净值", "4" => "流转", "5" => "秒还", "6" => "易居宝", 7 => "担保"),
            'borrow_status' => array("-1" => "尚未发布", "0" => "等待审核", "1" => "审核通过", "3" => "满额成功", "2" => "审核未通过", "4" => "满额未发布", "5" => "满标审核未通过"),
            'borrow_use' => array("244" => "短期周转", "245" => "生意周转", "246" => "生活周转",
                "247" => "购物消费", "248" => "不提现借款", "249" => "其它借款",
                "250" => "创业借款"),
            'borrow_time_limit' => array("1" => "1个月", "2" => "2个月", "3" => "3个月", "6" => "6个月", "9" => "9个月", "10" => "10个月", "12" => "12个月", "18" => "18个月", "24" => "24个月", "36" => "36个月"),
            'borrow_time_limit_search' => array("1" => "60天以下", "2" => "60-180天", "3" => "180-360天", "4" => "360天以上"),
            'borrow_day_time_limit' => array("3" => "3天", "4" => "4天", "5" => "5天", "6" => "6天", "7" => "7天", "8" => "8天",
                "9" => "9天", "10" => "10天", "11" => "11天", "12" => "12天", "13" => "13天", "14" => "14天",
                "15" => "15天", "16" => "16天", "17" => "17天", "18" => "18天", "19" => "19天", "20" => "20天",
                "21" => "21天", "22" => "22天", "23" => "23天", "24" => "24天", "25" => "25天", "26" => "26天",
                "27" => "27天", "28" => "28天", "29" => "29天", "30" => "30天"),
            'borrow_account' => array("1" => "10万以下", "2" => "10万-20万", "3" => "20-50万", "4" => "50万以上",),
            'borrow_transfer_account' => array("1" => "1万以下", "2" => "1-3万", "3" => "3-5万", "4" => "5万以上",),
            'borrow_apr' => array("1" => "10%以下 ", "2" => "10%-13%", "3" => "13%-15%", "4" => "15%以上"),
            'borrow_rate' => array("1" => "待定", "2" => "进行中 ", "3" => "已完成"),
            'borrow_style' => array("0" => "等额本息", "3" => "到期还本，按月付息"),
            'borrow_lowest_account' => array("50.00" => "50元", "100.00" => "100元", "0.00" => "无限制"),
            'borrow_most_account' => array("0.00" => "无限制", "1000.00" => "1000元", "10000.00" => "10000元", "18000.00" => "18000元"),
            'borrow_valid_time' => array("1" => "1天", "2" => "2天", "3" => "3天", "4" => "4天", "5" => "5天", "6" => "6天", "7" => "7天"),
            'borrow_fast_yongtu' => array("0" => "经营", "2" => "创业", "3" => "购房", "4" => "买车", "5" => "装修", "6" => "结婚", "7" => "旅游", "8" => "购物", "9" => "求学", "10" => "其他"),
            'borrow_fast_mortgage' => array("有" => "有", "无" => "无"),
            'borrow_fast_diya' => array("0" => "房产", "1" => "汽车", "2" => "有价证券", "3" => "其他"),
            'borrow_fast_ddlage' => array("22岁以下" => "22岁以下", "22-30岁" => "22-30岁", "31-40岁" => "31-40岁", "41-50岁" => "41-50岁", "50岁以上" => "50岁以上"),
            'borrow_fast_ddloccupation' => array("董事/总经理/总裁" => "董事/总经理/总裁","总监/经理/主管" => "总监/经理/主管","职员/其他"=>"职员/其他"),
            'borrow_fast_ddlincome' => array("50000以上" => "50000元以上"),
            'borrow_fast_ddlindustry' => array("IT/通信/电子/互联网" => "IT/通信/电子/互联网","金融业" => "金融业","房地产/建筑业" => "房地产/建筑业","商业服务" => "商业服务","贸易/批发/零售/租赁业" => "贸易/批发/零售/租赁业","文体教育/工艺美术" => "文体教育/工艺美术","生产/加工/制造" => "生产/加工/制造","交通/运输/物流/仓储" => "交通/运输/物流/仓储","服务业" => "服务业","文化/传媒/娱乐/体育" => "文化/传媒/娱乐/体育","能源/矿产/环保" => "能源/矿产/环保","政府/非盈利机构" => "政府/非盈利机构","农/林/牧/渔/其他" => "农/林/牧/渔/其他"),
            'borrow_fast_ddlturnover' => array("100万以下" => "100万以下", "100万-500万" => "100万-500万", "500万-2000万" => "500万-2000万", "2000万以上" => "2000万以上",),
            'borrow_fast_ddlstaff' => array("0-49人" => "0-49人", "50-100人" => "50-100人", "100-500人" => "100-500人", "500人以上" => "500人以上"),
            'borrow_fast_sex' => array("0" => "男", "1" => "女"),
            'user_self' => array("0" => "客户", "1" => "马甲"),
            'borrow_tender_status' => array("0" => "待审核", "1" => "成功", "2" => "失败"),
        );

        if ($key && isset($data[$key])) {
            return $data[$key];
        } else {
            return array();
        }
    }

    /**
     * 发标
     * @param $data
     */
    function add($data = array()) {
        $this->db->trans_start();
        if ($data['ftype'] == 5) {
            $mode = $data['user_id'] % 100;
            $user_account = $this->Account_model->get_account($data['user_id']);
            $log['user_id'] = $user_account['user_id'];
            $log['ftype'] = INVEST_MIAOBIAO; //冻结资金
            $log['money'] = ($data['apr'] * $data['account'] / (100 * 12));
            $log['total'] = $user_account['total'];
            $log['use_money'] = $user_account['use_money'] - $log['money'];
            $log['no_use_money'] = $user_account['no_use_money'] + $log['money'];
            $log['collection'] = $user_account['collection'];
            $log['to_user'] = 1;
            $log['remark'] = "发布秒标冻结资金";
            $log['add_time'] = time();
            $log['addip'] = $data['addip'];

            $this->db->insert('zjy_account_log_' . $mode, $log);
            $this->db->query("update zjy_account set use_money=use_money-{$log['money']},no_use_money=no_use_money+{$log['money']} where user_id={$data['user_id']}");
        }

        $this->db->insert('zjy_borrow', $data);
        $borrow_id = $this->db->insert_id();
        $this->db->trans_complete();
        if ($this->db->trans_status() == 1) {
            return $borrow_id;
        }
        return 0;
    }

    /**
     * 审标
     * @param int $id 标id
     * @param array $data
     * @return number
     */
    function verify($id, $data = array()) {
        $this->db->trans_start();
        $fstatus = $data['fstatus'];
        $borrow = $this->Borrow_model->get_borrow_obj($id);
        if ($fstatus == 1 && $borrow['ftype'] == 4) {//流转标先扣除借款额度
            $this->load->model('User_amount_model');
            $user_amount = $this->User_amount_model->get_one($borrow['user_id']);
            $uamount_log['user_id'] = $borrow['user_id'];
            $uamount_log['ftype'] = AMOUNT_BORROW_SUCCESS;
            $uamount_log['amount_type'] = 1;
            $uamount_log['account'] = $borrow['account'];
            $uamount_log['account_all'] = $user_amount['credit'] - $uamount_log['account'];
            $uamount_log['account_use'] = $user_amount['credit_use'] - $uamount_log['account'];
            $uamount_log['account_nouse'] = $user_amount['credit_nouse'];
            $uamount_log['remark'] = "借款成功，扣除额度";
            $uamount_log['add_time'] = time();
            $uamount_log['addip'] = $this->js->get_ip();
            $this->db->insert('zjy_user_amount_log', $uamount_log);
            $this->db->query("update zjy_user_amount set credit_use=credit_use-{$uamount_log['account']}
								where user_id={$borrow['user_id']}");
        }
        if ($fstatus == 2 && $borrow['ftype'] == 5) {
            $mode = $borrow['user_id'] % 100;
            $user_account = $this->Account_model->get_account($data['user_id']);
            $log['user_id'] = $user_account['user_id'];
            $log['ftype'] = BORROW_FROST; //扣除冻结款
            $log['money'] = ($borrow['apr'] * $borrow['account'] / (100 * 12));
            $log['total'] = $user_account['total'];
            $log['use_money'] = $user_account['use_money'] + $log['money'];
            $log['no_use_money'] = $user_account['no_use_money'] - $log['money'];
            $log['collection'] = $user_account['collection'];
            $log['to_user'] = 1;
            $log['remark'] = "对[<a href=/borrow/obj/{$id}.html target=_blank>{$borrow['title']}</a>]借款的解冻";
            $log['add_time'] = time();
            $log['addip'] = $this->js->get_ip();

            $this->db->insert('zjy_account_log_' . $mode, $log);
            $this->db->query("update zjy_account set use_money=use_money+{$log['money']},no_use_money=no_use_money-{$log['money']} where user_id={$borrow['user_id']}");
        }
        self::update($id, $data);
        if ($borrow['ftype'] != 3 && $borrow['ftype'] != 5) {
            $this->db->query("update zjy_user set is_loan=1 where user_id={$borrow['user_id']}");
        }
        $this->db->trans_complete();
        if ($this->db->trans_status() == 1) {
            return 1;
        }
        return 0;
    }

    /**
     * 发标
     * @param $data
     */
    function add_fast($data = array()) {
        $this->db->insert('zjy_borrow_fast', $data);
        return $this->db->insert_id();
    }

    /**
     * 添加自动投标信息
     * @param array $data
     */
    function add_borrow_auto($data = array()) {
        $this->db->insert('zjy_borrow_auto', $data);
        $key = 'auto_tender_count';
        $this->mycache->delete($key);
        return $this->db->insert_id();
    }

    /**
     * 修改标信息
     * @param $data
     */
    function update($id, $data) {
        $this->db->where('id', $id);
        $this->db->update('borrow', $data);
        return $this->db->affected_rows();
    }

    /**
     * 修改标信息
     * @param $data
     */
    function update_fast($id, $data) {
        $this->db->where('id', $id);
        $this->db->update('zjy_borrow_fast', $data);
        return $this->db->affected_rows();
    }

    /**
     * 删除标
     * @param $data
     */
    function delete($data = array()) {
        $this->db->where('id', $data['id']);
        $this->db->update('zjy_borrow', array('is_del' => 1));
    }

    /**
     * 查询
     * @param $data
     */
    function get_borrow_obj($id, $data = array()) {
        $select = "*";
        if (isset($data['select']) && $data['select'] == 1) {
            $select = "id,user_id,title,ftype,fstatus,fuse,time_limit,style,account,account_yes,apr,
						lowest_account,most_account,award,funds,content,repay_from,risk_manage,publish_remark,is_day,time_limit_day,success_time,
						lz_times,is_dxb,dxb_pwd,tender_times,verify_time,is_mjb,valid_time,monthly_repayment,
						repayment_account,repayment_yesaccount,repayment_time,end_time,each_time,lz_endtime,
                                                auto_verify_time,is_check,title_img,thumbnail,verify_remark,project_number,recommend_id,
                                                guarantee_id,borrow_fee, cltroGoods ,open_time";
        }
        $this->db->select($select);
        $this->db->where('id', $id);
        $query = $this->db->get('zjy_borrow');
        $result = $query->row_array();
        //对查询到的结果做处理，加上编号对应的名字
        $borrow_use = self::arrays('borrow_use');
        $result['fuse_name'] = $borrow_use[$result['fuse']];
        return $result;
    }

    /**
     * 查询
     * @param $data
     */
    function get_borrow_repayment_obj($id) {
        $select = "*";
        $this->db->select($select);
        $this->db->where('id', $id);
        $query = $this->db->get('zjy_borrow_repayment');
        return $query->row_array();
    }

    function get_borrow_tender_obj($id, $data = array()) {
        $select = "*";
        if (isset($data['select']) && $data['select'] == 1) {
            $select = "id,user_id,fstatus,borrow_id,money,account,repayment_account,interest,is_exp,is_exp_repay
						repayment_yesaccount,repayment_yesinterest,wait_account,wait_interest,add_time ";
        }
        $this->db->select($select);
        $this->db->where('id', $id);
        $query = $this->db->get('zjy_borrow_tender');
        return $query->row_array();
    }

    function get_borrow_tender_list($data = array()) {
        $select = "*";
        if (isset($data['select']) && $data['select'] == 1) {
            $select = " t1.id,t1.user_id,t1.fstatus,t1.borrow_id,t1.money,t1.account,t1.repayment_account,t1.interest,
						t1.repayment_yesaccount,t1.repayment_yesinterest,t1.wait_account,t1.wait_interest,t1.add_time,
						t2.title
						";
        }

        //封装条件
        $_where = " where 1=1 ";
        if (isset($data['where']['borrow_id']) && $data['where']['borrow_id'] > 0) {
            $_where .= " and t1.borrow_id = " . $data['where']['borrow_id'];
        }
        if (isset($data['where']['fstatus']) && $data['where']['fstatus'] != '') {
            $_where .= " and t1.fstatus = " . $data['where']['fstatus'];
        }
        if (isset($data['where']['user_id']) && $data['where']['user_id'] > 0) {
            $_where .= " and t1.user_id = " . $data['where']['user_id'];
        }

        $page_size = $data['page_size'];
        $page_start = $data['page_start'];

        //排序
        $_order = " order by t1.id desc ";

        //封装sql
        $sql_result = "select $select from zjy_borrow_tender as t1 left join zjy_borrow as t2 on t1.borrow_id=t2.id";
        $sql_result .= $_where;
        $sql_result .= $_order;
        $sql_result .= " limit $page_start, $page_size";

        $query = $this->db->query($sql_result);
        $borrow_tender_list = $query->result_array();
        if (count($borrow_tender_list) < 1) {
            return array();
        }
        return $borrow_tender_list;
    }

    function index_borrow_tender_list($data = array()) {
        $mkey = "index_borrow_tender_list";
        //$this->mycache->delete($mkey);
        $ret = $this->mycache->get_array($mkey);
        if ($ret != false) {
            return $ret;
        }

        $select = "t1.id,t1.borrow_id,t1.user_id,t2.username,t1.account,t1.add_time,t3.title";

        //封装条件
        $_where = " where t1.account>0 ";

        $page_size = $data['page_size'];
        $page_start = $data['page_start'];

        //排序
        $_order = " order by t1.id desc ";

        //封装sql
        $sql_result = "select $select from zjy_borrow_tender as t1 left join zjy_user as t2 on t1.user_id=t2.user_id left join zjy_borrow as t3 on t1.borrow_id=t3.id";
        $sql_result .= $_where;
        $sql_result .= $_order;
        $sql_result .= " limit $page_start, $page_size";

        $query = $this->db->query($sql_result);
        $borrow_tender_list = $query->result_array();
        if (count($borrow_tender_list) < 1) {
            return array();
        }
        $this->mycache->set_array($mkey, $borrow_tender_list, 180);
        return $borrow_tender_list;
    }

    function borrow_tender_user_list($data = array()) {
        $select = "t1.id,t1.borrow_id,t1.repayment_account,t1.interest,t1.user_id,t1.fstatus,t2.username,t1.account,t1.money,t1.add_time,t3.title,t3.ftype,t3.apr,t3.time_limit,t3.is_day,t3.time_limit_day";

        //封装条件
        $_where = " where 1=1 ";

        if (isset($data['where']['user_id']) && $data['where']['user_id'] != '') {
            $_where .= " and t1.user_id = " . $data['where']['user_id'];
        }
        if (isset($data['where']['username']) && $data['where']['username'] != '') {
            $_where .= " and t2.username = '" . trim($data['where']['username']) . "'";
        }

        if (isset($data['where']['is_self']) && $data['where']['is_self'] != -1) {
            $_where .= " and t2.is_self=" . $data['where']['is_self'];
        }

        if (isset($data['where']['fstatus']) && $data['where']['fstatus'] != -1) {
            $_where .= " and t1.fstatus=" . $data['where']['fstatus'];
        }

        if (isset($data['where']['no_del']) && $data['where']['no_del'] == 1) {
            $_where .= " and t1.fstatus <> 2";
        }

        if (isset($data['where']['strtime']) && $data['where']['strtime'] != 0) {
            $strtime = strtotime($data['where']['strtime'] . ' 00:00:00');
            $_where .= " and t1.add_time >= " . $strtime;
        }
        if (isset($data['where']['endtime']) && $data['where']['endtime'] != 0) {
            $endtime = strtotime($data['where']['endtime'] . ' 23:59:59');
            $_where .= " and t1.add_time <= " . $endtime;
        }

        if (isset($data['where']['title']) && $data['where']['title'] != '') {
            $_where .= " and t3.title = '" . $data['where']['title'] . "'";
        }

        if (isset($data['where']['time_limit']) && $data['where']['time_limit'] != -1) {
            $_where .= " and t3.time_limit = " . $data['where']['time_limit'];
        }

        $page_size = $data['page_size'];
        $page_start = $data['page_start'];
        //排序
        $_order = " order by t1.id desc ";

        //封装sql
        $sql_result = "select $select from zjy_borrow_tender as t1 left join zjy_user as t2 on t1.user_id=t2.user_id left join zjy_borrow as t3 on t1.borrow_id=t3.id";
        $sql_result .= $_where;
        $sql_result .= $_order;

        if (isset($data['limit']) && $data['limit'] == 'all') {
            $query = $this->db->query($sql_result);
            $data['tender_list'] = $query->result_array();
            return $data;
        } else {
            $sql_result .= " limit $page_start, $page_size";
            $query = $this->db->query($sql_result);
            $data['tender_list'] = $query->result_array();
        }

        //总记录条数
        $sql_count = "select count(*) as count from zjy_borrow_tender as t1 left join zjy_user as t2 on t1.user_id=t2.user_id left join zjy_borrow as t3 on t1.borrow_id=t3.id";
        $sql_count .= $_where;
        $query = $this->db->query($sql_count);
        $data['tender_count'] = $query->row()->count;

        //投资总人数
        $sql_user_count = "select count(DISTINCT(t2.user_id)) as count from zjy_borrow_tender as t1 left join zjy_user as t2 on t1.user_id=t2.user_id left join zjy_borrow as t3 on t1.borrow_id=t3.id";
        $sql_user_count .= $_where;
        $query = $this->db->query($sql_user_count);
        $data['tender_user_count'] = $query->row()->count;

        //投资金额
        $sql_money_sum = "select sum(t1.money) as count from zjy_borrow_tender as t1 left join zjy_user as t2 on t1.user_id=t2.user_id left join zjy_borrow as t3 on t1.borrow_id=t3.id";
        $sql_money_sum .= $_where;

        $query = $this->db->query($sql_money_sum);
        $data['tender_money_count'] = $query->row()->count;

        return $data;
    }

    function get_borrow_tender_lists($data = array()) {
        $select = "t1.*";
        if (isset($data['select']) && $data['select'] == 1) {
            $select = " t1.id,t1.user_id,t1.fstatus,t1.borrow_id,t1.money,t1.account,t1.repayment_account,t1.interest,
						t1.repayment_yesaccount,t1.repayment_yesinterest,t1.wait_account,t1.wait_interest,t1.add_time,
						t2.title,t2.apr,t2.time_limit,t2.is_day,t2.time_limit_day
						";
        }

        //封装条件
        $_where = " where 1=1 ";
        if (isset($data['where']['borrow_id']) && $data['where']['borrow_id'] > 0) {
            $_where .= " and t1.borrow_id = " . $data['where']['borrow_id'];
        }
        if (isset($data['where']['fstatus']) && $data['where']['fstatus'] != '') {
            $_where .= " and t2.fstatus = " . $data['where']['fstatus'];
        }
        if (isset($data['where']['user_id']) && $data['where']['user_id'] > 0) {
            $_where .= " and t1.user_id = " . $data['where']['user_id'];
        }

        $page_size = $data['page_size'];
        $page_start = $data['page_start'];

        //排序
        $_order = " order by t1.id desc ";

        //封装sql
        $sql_result = "select $select from zjy_borrow_tender as t1 left join zjy_borrow as t2 on t1.borrow_id=t2.id";
        $sql_result .= $_where;
        $sql_result .= $_order;
        $sql_result .= " limit $page_start, $page_size";
        $query = $this->db->query($sql_result);

        if (isset($data['list']) && $data['list'] == 1) {
            return $query->result_array();
        }
        $data['tender_list'] = $query->result_array();

        //总记录条数
        $sql_count = "select count(*) as count from zjy_borrow_tender as t1 left join zjy_borrow as t2 on t1.borrow_id=t2.id";
        $sql_count .= $_where;
        $query = $this->db->query($sql_count);
        $data['tender_count'] = $query->row()->count;
        return $data;
    }

    function get_borrow_tender($data = array()) {
        $select = "*";
        if (isset($data['select']) && $data['select'] == 1) {
            $select = "id,user_id,fstatus,borrow_id,money,account,repayment_account,interest,
						repayment_yesaccount,repayment_yesinterest,wait_account,wait_interest,add_time ";
        } elseif (isset($data['select']) && $data['select'] == 2) {
            $select = "user_id,fstatus,money,account,add_time ";
        }

        //封装条件
        $_where = " where 1=1 ";
        if (isset($data['where']['borrow_id']) && $data['where']['borrow_id'] > 0) {
            $_where .= " and borrow_id = " . $data['where']['borrow_id'];
        }
        if (isset($data['where']['fstatus']) && $data['where']['fstatus'] != '') {
            $_where .= " and fstatus = " . $data['where']['fstatus'];
        }
        if (isset($data['where']['user_id']) && $data['where']['user_id'] > 0) {
            $_where .= " and user_id = " . $data['where']['user_id'];
        }

        //排序
        $_order = " order by id desc ";
        $_limit = "";
        if (isset($data['page'])) {
            $page = intval($data['page']);
            $page = max($page, 1);
            $_start = ($page - 1) * 20;
            $_limit = " limit {$_start},20";
        }

        //封装sql
        $sql_result = "select $select from zjy_borrow_tender";
        $sql_result .= $_where;
        $sql_result .= $_order;
        $sql_result .= $_limit;
        $query = $this->db->query($sql_result);
        $borrow_tender_list = $query->result_array();
        if (count($borrow_tender_list) < 1) {
            return array();
        }
        return $borrow_tender_list;
    }

    function get_borrow_count($data = array()) {
        //封装条件
        $_where = " where 1=1 ";
        if (isset($data['where']['user_id']) && $data['where']['user_id'] != '') {
            $_where .= " and t1.user_id = " . $data['where']['user_id'];
        }
        if (isset($data['where']['fstatus']) && $data['where']['fstatus'] != '') {
            $_where .= " and t1.fstatus = " . $data['where']['fstatus'];
        }
        if (isset($data['where']['ftype']) && $data['where']['ftype'] != '') {
            $_where .= " and t1.ftype = " . $data['where']['ftype'];
        }
        $sql_count = "select count(*) as count from zjy_borrow as t1 ";
        $sql_count .= $_where;
        $query = $this->db->query($sql_count);
        return $query->row()->count;
    }

    /**
     * 投标
     * @param $data
     */
    function borrow_tender($data = array(), $is_exp = false,$reg_money = 0) {
        $id = $data['id'];
        $account = $data['account'];
        $ip = $data['ip'];
        $user_id = $data['user_id'];
        $borrow_user_id = $data['borrow_user_id'];
        $money = $data['money'];
        $mmmloan = $data['mmmloanno'];
        $this->load->model('Account_model');
        //开始事物
        $this->db->trans_start();
        //添加用户资金使用记录
        $user_account = $this->Account_model->get_account($user_id);
        $log['user_id'] = $user_id;
        $log['ftype'] = TENDER;
        $log['money'] = $account;
//        if($is_exp){
//        	$log['money'] = $account-EXP_MONEY;
//        }
        $log['total'] = $user_account['total'];
        $log['use_money'] = $user_account['use_money'] - $log['money'];
        $log['no_use_money'] = $user_account['no_use_money'] + $log['money'];
        $log['collection'] = $user_account['collection'];
        $log['to_user'] = $borrow_user_id;
        $log['op'] = 1;
        $log['remark'] = "投标冻结资金";
        $log['add_time'] = time();
        $log['addip'] = $ip;
        $mode = $user_id % 100;
        $this->db->insert('zjy_account_log_' . $mode, $log);
        //更新用户资金表
//    	if($is_exp){
//    		$expaccount =  $account-EXP_MONEY;
//        	$this->db->query("update zjy_account set use_money=use_money-{$expaccount},no_use_money=no_use_money+{$expaccount} where user_id={$user_id}");
//        }else{
//        	$this->db->query("update zjy_account set use_money=use_money-{$account},no_use_money=no_use_money+{$account} where user_id={$user_id}");
//        }
        $this->db->query("update zjy_account set use_money=use_money-{$account},no_use_money=no_use_money+{$account} where user_id={$user_id}");


        $borrow = self::get_borrow_obj($id);
        //更新投标表
        $this->db->query("update zjy_borrow set account_yes=account_yes+{$money},tender_times=tender_times+1 where id={$id}");
        //添加投标记录
        $t2data['user_id'] = $user_id;
        $t2data['borrow_id '] = $id;
        $t2data['money'] = $money;
        $t2data['account'] = $account;
        $t2data['add_time'] = time();
        $t2data['addip'] = $ip;
        if($is_exp){
        	$t2data['is_exp'] = 1;
        }
        $this->db->insert('zjy_borrow_tender', $t2data);
        $tender_id = $this->db->insert_id();

        $eq['account'] = $money;
        $eq['apr'] = $borrow['apr'];
        $eq['time_limit'] = $borrow['time_limit'];
        $eq['style'] = $borrow['style'];
        $eq['is_day'] = $borrow['is_day'];
        $eq['time_limit_day'] = $borrow['time_limit_day'];
        $result = equal_interest($eq);
        $repayment_account = 0;
        foreach ($result as $key => $value) {
            $repayment_account += $value['repayment_account'];
            //将归还信息写进去
            $bcdata['tender_id'] = $tender_id;
            $bcdata['borrow_id'] = $id;
            $bcdata['forder'] = $key;
            $bcdata['repay_time'] = $value['repayment_time'];
            $bcdata['repay_account'] = $value['repayment_account'];
            $bcdata['interest'] = $value['interest'];
            $bcdata['capital'] = $value['capital'];
            $bcdata['user_id'] = $user_id;
            $bcdata['add_time'] = time();
            $bcdata['addip'] = $ip;
            $this->db->insert('zjy_borrow_collection', $bcdata);
        }
        $_interest = $repayment_account - $account;
        $this->db->query("update zjy_borrow_tender set exp_money={$reg_money},repayment_account={$repayment_account},wait_account ={$repayment_account},interest = {$_interest},wait_interest = {$_interest},mmm_loanno='{$mmmloan}' where id={$tender_id}");
        $this->db->trans_complete();
        if ($this->db->trans_status() === TRUE) {
            return 1;
        }
        return 0;
    }

    /**
     * 投流转标
     * @param $data
     */
    function borrow_lz_tender($data = array()) {
        $id = $data['id'];
        $ip = $data['ip'];
        $user_id = $data['user_id'];
        $money = $data['money'];
        $account = $data['account'];
        $borrow = self::get_borrow_obj($data['id']);
        $this->load->model('Account_model');
        $this->load->model('User_model');
        $this->load->model('Message_model');
        $this->load->model('Credit_model');
        $borrow_url = "<a href='/borrow/obj/{$borrow['id']}.html' target=_blank>{$borrow['title']}</a>";
        $this->db->trans_start();
        //第一次投标，更新标状态和复审时间复审备注
        if ($borrow['tender_times'] < 1) {
            $this->db->query("update zjy_borrow set fstatus=3,repayment_time=" . time() . ",repayment_remark='流转标自动复审' where id={$borrow['id']}");
        }
        $this->db->query("update zjy_borrow set account_yes=account_yes+{$data['account']},tender_times=tender_times+1  where id='{$borrow['id']}'");

        $t2data['add_time'] = time();
        $t2data['addip'] = $ip;
        $t2data['user_id'] = $user_id;
        $t2data['borrow_id '] = $id;
        $t2data['money'] = $money;
        $t2data['account'] = $account;
        $t2data['fstatus'] = 1;
        $this->db->insert('zjy_borrow_tender', $t2data);
        $tender_id = $this->db->insert_id();

        if ($tender_id > 0) {
            //如果成功，则将还款信息输进表里面去
            $eq['account'] = $account;
            $eq['apr'] = $borrow['apr'];
            $eq['time_limit'] = $borrow['time_limit'];
            $eq['style'] = $borrow['style'];
            $eq['is_day'] = $borrow['is_day'];
            $eq['time_limit_day'] = $borrow['time_limit_day'];
            $result = equal_interest($eq);
            $repayment_account = 0;
            $collection_id = 0;
            foreach ($result as $key => $value) {
                $repayment_account += $value['repayment_account'];
                //将归还信息写进去
                $this->db->query("insert into zjy_borrow_collection set user_id=$user_id,borrow_id=$id,add_time=" . time() . ",addip='{$ip}',
						`tender_id`='{$tender_id}',`forder`='{$key}',`repay_time`='{$value['repayment_time']}',
						`repay_account`='{$value['repayment_account']}',`interest`='{$value['interest']}',
						`capital`='{$value['capital']}'");
                if ($borrow['time_limit'] >= 12 && $value['capital'] > 0) {
                    $collection_id = $this->db->insert_id();
                }
            }
            $_interest = round($repayment_account - $data['account'], 2);
            $this->db->query(" update zjy_borrow_tender set repayment_account='{$repayment_account}',
								wait_account ='{$repayment_account}',interest = '{$_interest}',
								wait_interest = '{$_interest}' where id={$tender_id}");

            //投标金额冻结
            $mode = $user_id % 100;
            $account_result = $this->Account_model->get_account($user_id);
            $log['user_id'] = $user_id;
            $log['ftype'] = TENDER;
            $log['money'] = $account;
            $log['total'] = $account_result['total'];
            $log['use_money'] = $account_result['use_money'] - $log['money'];
            $log['no_use_money'] = $account_result['no_use_money'] + $log['money'];
            $log['collection'] = $account_result['collection'];
            $log['to_user'] = $borrow['user_id'];
            $log['remark'] = "投标冻结资金";
            $log['add_time'] = time();
            $log['addip'] = $ip;
            $this->db->insert('zjy_account_log_' . $mode, $log);
            $this->db->query("update zjy_account set use_money=use_money-{$log['money']},no_use_money=no_use_money+{$log['money']} where user_id={$user_id}");


            //扣除投资者的金钱。
            unset($account_result);
            unset($log);
            $account_result = $this->Account_model->get_account($user_id);
            $log['user_id'] = $user_id;
            $log['ftype'] = INVEST;
            $log['money'] = $account;
            $log['total'] = $account_result['total'] - $log['money'];
            $log['use_money'] = $account_result['use_money'];
            $log['no_use_money'] = $account_result['no_use_money'] - $log['money'];
            $log['collection'] = $account_result['collection'];
            $log['to_user'] = $borrow['user_id'];
            $log['remark'] = "投标成功费用扣除";
            $log['add_time'] = time();
            $log['addip'] = $ip;
            $this->db->insert('zjy_account_log_' . $mode, $log);
            $this->db->query("update zjy_account set total=total-{$log['money']},no_use_money=no_use_money-{$log['money']} where user_id={$user_id}");


            //添加待收的金额
            unset($account_result);
            unset($log);
            $account_result = $this->Account_model->get_account($user_id);
            $log['user_id'] = $user_id;
            $log['ftype'] = COLLECTION;
            $log['money'] = $repayment_account;
            $log['total'] = $account_result['total'] + $log['money'];
            $log['use_money'] = $account_result['use_money'];
            $log['no_use_money'] = $account_result['no_use_money'];
            $log['collection'] = $account_result['collection'] + $log['money'];
            $log['to_user'] = $borrow['user_id'];
            $log['remark'] = "待收金额";
            $log['add_time'] = time();
            $log['addip'] = $ip;
            $this->db->insert('zjy_account_log_' . $mode, $log);
            $this->db->query("update zjy_account set total=total+{$log['money']},collection=collection+{$log['money']} where user_id={$user_id}");

            //提醒设置
            $this->Message_model->send(array('sent_user' => 1, 'receive_user' => $user_id,
                'name' => "投资的标[<font color=red>{$borrow['title']}</font>投标成功",
                'fstatus' => 0, 'message_type' => 'system', 'sented' => 0, 'deltype' => 0,
                'content' => "你所投资的标[<a href='/borrow/obj/{$id}.html' target=_blank><font color=red>{$borrow['title']}</font></a>]在" . date("Y-m-d", time()) . "已经通过",
                'add_time' => time(), 'addip' => $ip));


            /* if ($borrow['is_day']==1){
              $credit_value = round($account/100*$borrow['apr']/100*($borrow['time_limit_day']/30));
              }else{
              $credit_value = round($account/100*$borrow['apr']/100*$borrow['time_limit']);
              } */

            $vals = array(
                1 => 16,
                3 => 38,
                6 => 58,
                9 => 78,
                12 => 98,
                18 => 118,
                24 => 128,
                36 => 218
            );
            $credit_value = intval($account / 10000 * $vals[$borrow['time_limit']]);
            //晚上双倍
            $st = strtotime(date('Y-m-d 06:00:00'));
            $et = strtotime(date('Y-m-d 18:00:00'));
            $now = time();
            if ($now < $st || $now > $et) {
                $credit_value = $credit_value * 2;
            }
            //增加积分
            $creditNidType = $this->Credit_model->arrays('creditNidType');
            $creditTypeName = $this->Credit_model->arrays('creditTypeName');
            $credit_log = array('user_id' => $user_id,
                'type_id' => $creditNidType['invest_success'],
                'op' => 1,
                'credit_value' => $credit_value,
                'remark' => $creditTypeName[$creditNidType['invest_success']] . '加' . $credit_value . '分',
                'op_user' => $borrow['user_id'],
                'add_time' => time(),
                'addip' => $ip);
            $this->Credit_model->incr_credit($credit_log);

            //借款者总金额增加。
            unset($account_result);
            unset($log);
            $mode1 = $borrow['user_id'] % 100;
            $account_result = $this->Account_model->get_account($borrow['user_id']);
            $log['user_id'] = $borrow['user_id'];
            $log['ftype'] = BORROW_SUCCESS;
            $log['money'] = $account;
            $log['total'] = $account_result['total'] + $log['money'];
            $log['use_money'] = $account_result['use_money'] + $log['money'];
            $log['no_use_money'] = $account_result['no_use_money'];
            $log['collection'] = $account_result['collection'];
            $log['to_user'] = "0";
            $log['remark'] = "通过[{$borrow_url}]借到的款";
            $log['add_time'] = time();
            $log['addip'] = $ip;
            $this->db->insert('zjy_account_log_' . $mode1, $log);
            $this->db->query("update zjy_account set total=total+{$log['money']},use_money=use_money+{$log['money']} where user_id={$borrow['user_id']}");

            //冻结借款标的保证金10%。
            unset($account_result);
            unset($log);
            $account_result = $this->Account_model->get_account($borrow['user_id']);
            $log['user_id'] = $borrow['user_id'];
            $log['ftype'] = MARGIN;
            $log['money'] = $data['account'] * 0.1;
            $log['total'] = $account_result['total'];
            $log['use_money'] = $account_result['use_money'] - $log['money'];
            $log['no_use_money'] = $account_result['no_use_money'] + $log['money'];
            $log['collection'] = $account_result['collection'];
            $log['to_user'] = "0";
            $log['remark'] = "冻结借款标的[{$borrow_url}]的保证金";
            $log['add_time'] = time();
            $log['addip'] = $ip;
            //如果保证金等于0，那不在写记录了
            if ($log['money'] <> 0) {
                $this->db->insert('zjy_account_log_' . $mode1, $log);
                $this->db->query("update zjy_account set use_money=use_money-{$log['money']},no_use_money=no_use_money+{$log['money']} where user_id={$borrow['user_id']}");
                //更新保证金
                $this->db->query("update zjy_borrow set forst_account=forst_account+{$log['money']} where id='{$borrow['id']}'");
            }

            unset($account_result);
            unset($log);
            $borrow_fee = 0;
            $borrow_fee = round($borrow['time_limit'] * 0.005 * $account, 2);
            $account_result = $this->Account_model->get_account($borrow['user_id']);
            $log['user_id'] = $borrow['user_id'];
            $log['ftype'] = BORROW_FEE;
            $log['money'] = $borrow_fee;
            $log['total'] = $account_result['total'] - $log['money'];
            $log['use_money'] = $account_result['use_money'] - $log['money'];
            $log['no_use_money'] = $account_result['no_use_money'];
            $log['collection'] = $account_result['collection'];
            $log['to_user'] = "0";
            $log['remark'] = "借款[{$borrow_url}]的手续费";
            $log['add_time'] = time();
            $log['addip'] = $ip;
            $this->db->insert('zjy_account_log_' . $mode1, $log);
            $this->db->query("update zjy_account set total=total-{$log['money']},use_money=use_money-{$log['money']} where user_id={$borrow['user_id']}");

            $nowtime = time();
            $endtime = get_times(array("num" => $borrow['time_limit'], "time" => $nowtime));
            $_each_time = "每月" . date("d", $nowtime) . "日";
            $this->db->query("update zjy_borrow set success_time='{$nowtime}',end_time='{$endtime}',each_time='{$_each_time}',
					 			payment_account=payment_account+'{$repayment_account}'
					 			where id='{$borrow['id']}'");

            //是否使用了体验金
            $use_exp_money = 0;
            if ($borrow['time_limit'] == 12) {
                $account_result = $this->Account_model->get_account($user_id);
                if ($account_result['exp_money_12'] > 0 || $account_result['exp_money_24'] > 0) {
                    //如果有12月体验金，使用12月体验金
                    $exp_money_12 = $account_result['exp_money_12'] - $account;
                    //12月体验金不足，继续使用24月体验金
                    if ($exp_money_12 < 0) {
                        $exp_money_24 = $account_result['exp_money_24'] + $exp_money_12;
                    }
                    $exp_money_12 = max(0, $exp_money_12);
                    $exp_money_24 = max(0, $exp_money_24);
                    $use_exp_money_12 = $account_result['exp_money_12'] - $exp_money_12;
                    $use_exp_money_24 = $account_result['exp_money_24'] - $exp_money_24;
                    $use_exp_money = $use_exp_money_12 + $use_exp_money_24; //投标使用的体验金
                    //修改账户体验金备注
                    $sql = "update zjy_account set exp_money_12={$exp_money_12},exp_money_24={$exp_money_24} where user_id=$user_id";
                    $this->db->query($sql);
                }
            } elseif ($borrow['time_limit'] == 24) {
                $account_result = $this->Account_model->get_account($user_id);
                if ($account_result['exp_money_24'] > 0) {
                    $exp_money_24 = $account_result['exp_money_24'] - $account;
                    $exp_money_24 = max(0, $exp_money_24);
                    $use_exp_money_24 = $account_result['exp_money_24'] - $exp_money_24;
                    $use_exp_money = $use_exp_money_24;
                    //修改账户体验金备注
                    $sql = "update zjy_account set exp_money_24={$exp_money_24} where user_id=$user_id";
                    $this->db->query($sql);
                }
            }
            //如果使用了体验金，需记录且回款后扣除
            if ($use_exp_money > 0) {
                $deductArr = array(
                    'user_id' => $user_id,
                    'collection_id' => $collection_id,
                    'exp_money' => $use_exp_money
                );
                $this->db->insert('zjy_expmoney_deduct', $deductArr);
            }


            //投标返现奖励
            $fxtime = strtotime('2014-08-18');
            $fxEndtime = strtotime('2014-08-25');
            $now = time();
            if ($now > $fxtime && $now < $fxEndtime && $borrow['is_day'] == 0 && $borrow['time_limit'] >= 6 && $account >= 10000) {
                $fanxianArr = array(
                    6 => 0.0023,
                    9 => 0.0032,
                    12 => 0.0035,
                    18 => 0.0038
                );
                $fanxianMoney = round($account * $fanxianArr[$borrow['time_limit']], 2);
                unset($account_result);
                unset($log);
                $account_result = $this->Account_model->get_account($user_id);
                $log['user_id'] = $user_id;
                $log['ftype'] = INVEST_FANXIAN;
                $log['money'] = $fanxianMoney;
                $log['total'] = $account_result['total'] + $log['money'];
                $log['use_money'] = $account_result['use_money'] + $log['money'];
                $log['no_use_money'] = $account_result['no_use_money'];
                $log['collection'] = $account_result['collection'];
                $log['to_user'] = $borrow['user_id'];
                $log['remark'] = "投标返现奖励";
                $log['add_time'] = $now;
                $log['addip'] = $ip;
                //$mode = $user_id%100;
                $this->db->insert('zjy_account_log_' . $mode, $log);
                $this->db->query("update zjy_account set total=total+{$log['money']},use_money=use_money+{$log['money']} where user_id={$user_id}");

                //是否被邀请的新用户，是的话给邀请人发放奖励
                $userInfo = $this->User_model->get_by_uid($user_id);
                if ($userInfo['add_time'] > $fxtime && $userInfo['invite_userid'] > 0) {
                    unset($account_result);
                    unset($log);

                    $inviteAward = 0.0005;
                    $inviteMoney = round($account * $inviteAward, 2);
                    $account_result = $this->Account_model->get_account($userInfo['invite_userid']);
                    $log['user_id'] = $userInfo['invite_userid'];
                    $log['ftype'] = INVITE_REWARD;
                    $log['money'] = $inviteMoney;
                    $log['total'] = $account_result['total'] + $log['money'];
                    $log['use_money'] = $account_result['use_money'] + $log['money'];
                    $log['no_use_money'] = $account_result['no_use_money'];
                    $log['collection'] = $account_result['collection'];
                    $log['to_user'] = 1;
                    $log['remark'] = "邀请奖励";
                    $log['add_time'] = $now;
                    $log['addip'] = $ip;
                    $mode2 = $userInfo['invite_userid'] % 100;
                    $this->db->insert('zjy_account_log_' . $mode2, $log);
                    $this->db->query("update zjy_account set total=total+{$log['money']},use_money=use_money+{$log['money']} where user_id={$userInfo['invite_userid']}");
                    $this->db->query("update zjy_user set invite_money=invite_money+{$log['money']} where user_id={$user_id}");
                }
            }


            //奖励体验金
            if ($borrow['is_day'] == 0 && $borrow['time_limit'] >= 12 && $account >= 10000) {
                $borrowLimit = $borrow['time_limit']; //投标期限12还是24月标
                $expMoney = intval($account / 10000) * 100; //计算应获体验金
                //添加资金记录修改账户信息
                unset($account_result);
                unset($log);
                $account_result = $this->Account_model->get_account($user_id);
                $log['user_id'] = $user_id;
                $log['ftype'] = EXP_MONEY;
                $log['money'] = $expMoney;
                $log['total'] = $account_result['total'] + $log['money'];
                $log['use_money'] = $account_result['use_money'] + $log['money'];
                $log['no_use_money'] = $account_result['no_use_money'];
                $log['collection'] = $account_result['collection'];
                $log['to_user'] = $borrow['user_id'];
                $log['remark'] = "投标成功获得体验金";
                $log['add_time'] = time();
                $log['addip'] = $ip;
                //$mode = $user_id%100;
                $this->db->insert('zjy_account_log_' . $mode, $log);

                if ($borrow['time_limit'] >= 24) {
                    $this->db->query("update zjy_account set total=total+{$log['money']},use_money=use_money+{$log['money']},exp_money_24=exp_money_24+{$log['money']} where user_id={$user_id}");
                } else {
                    $this->db->query("update zjy_account set total=total+{$log['money']},use_money=use_money+{$log['money']},exp_money_12=exp_money_12+{$log['money']} where user_id={$user_id}");
                }
            }

            //如果有设置奖励并且招标成功
            if ($borrow['award'] == 2 || $borrow['funds'] > 0) {
                //投标奖励扣除和增加。
                $money = round((($borrow['funds'] / 100) * $account), 2);

                unset($account_result);
                unset($log);
                $account_result = $this->Account_model->get_account($user_id);
                $log['user_id'] = $user_id;
                $log['ftype'] = AWARD_ADD;
                $log['money'] = $money;
                $log['total'] = $account_result['total'] + $log['money'];
                $log['use_money'] = $account_result['use_money'] + $log['money'];
                $log['no_use_money'] = $account_result['no_use_money'];
                $log['collection'] = $account_result['collection'];
                $log['to_user'] = $borrow['user_id'];
                $log['remark'] = "借款[{$borrow_url}]的奖励";
                $log['add_time'] = time();
                $log['addip'] = $ip;
                $this->db->insert('zjy_account_log_' . $mode, $log);
                $this->db->query("update zjy_account set total=total+{$log['money']},use_money=use_money+{$log['money']} where user_id={$user_id}");

                unset($account_result);
                unset($log);
                $account_result = $this->Account_model->get_account($borrow['user_id']);
                $log['user_id'] = $borrow['user_id'];
                $log['ftype'] = AWARD_LOWER;
                $log['money'] = $money;
                $log['total'] = $account_result['total'] - $log['money'];
                $log['use_money'] = $account_result['use_money'] - $log['money'];
                $log['no_use_money'] = $account_result['no_use_money'];
                $log['collection'] = $account_result['collection'];
                $log['to_user'] = $user_id;
                $log['remark'] = "扣除借款[{$borrow_url}]的奖励";
                $log['add_time'] = time();
                $log['addip'] = $ip;
                $this->db->insert('zjy_account_log_' . $mode1, $log);
                $this->db->query("update zjy_account set total=total-{$log['money']},use_money=use_money-{$log['money']} where user_id={$borrow['user_id']}");
            }

            $this->db->trans_complete();
            if ($this->db->trans_status() == 1) {
                //添加到邮件发送队列
                $protocolMailKey = "protocolMailKey";
                $mailList = $this->mycache->get_array($protocolMailKey);
                $mailList = $mailList ? $mailList : array();
                $mailList[] = array(
                    'user_id' => $user_id,
                    'borrow_id' => $id,
                    'borrow_title' => $borrow['title'],
                    'tender_id' => $tender_id
                );
                $this->mycache->set_array($protocolMailKey, $mailList);

//				$this->load->library('func');
//				$html = $this->func->protocol_msg($id, $tender_id);
//
////				$this->load->library('/MPDF56/mpdf');
////				$this->mpdf->useAdobeCJK = true;
////				$this->mpdf->SetAutoFont(AUTOFONT_ALL);
////				$this->mpdf->SetDisplayMode('fullpage');
////				$this->mpdf->showWatermarkText = true;
////				$this->mpdf->SetAutoFont();
////
////				$this->mpdf->showWatermarkText = true;
////				$this->mpdf->SetAutoFont();
////
////				$this->mpdf->WriteHTML($html);
////				$filename = "./static/No".$id."_".$tender_id.".pdf";
////				$this->mpdf->Output($filename);
//
//				$this->load->library('/phpmailer/PHPMailer');
//				$this->phpmailer->IsSMTP();
//				$user_info = $this->User_model->get_by_uid($user_id);
//				$this->phpmailer->AddAddress("admin@".CON_WEBURL2, CON_PLATFORMNAME);//收件人
//				$this->phpmailer->AddBCC($user_info['email'],$user_info['username']);//抄送
//				$this->phpmailer->Subject 	= "借款标“{$borrow['title']}”的借款协议书（可到网站下载PDF格式）";
//				$this->phpmailer->Body 		= $html;
//				//$this->phpmailer->AddAttachment($filename);
//				$this->phpmailer->AltBody = "This is the body in plain text for non-HTML mail clients";
//				$this->phpmailer->Send();
                return 1;
            }
        } else {
            $this->db->trans_rollback();
            return 0;
        }
    }

    function reg_money_use($data = array()) {
        $user_id = isset($data['user_id']) ? $data['user_id'] : 0;
        if ($user_id > 0) {
            $this->load->model('Account_model');
            $user_account = $this->Account_model->get_account($user_id);
            $log = array(
                'user_id' => $user_id,
                'ftype' => REG_MONEY,
                'money' => 100,
                'total' => $user_account['total'],
                'use_money' => $user_account['use_money'] + 100,
                'no_use_money' => $user_account['no_use_money'],
                'collection' => $user_account['collection'],
                'to_user' => 0,
                'add_time' => time(),
                'addip' => $this->js->get_ip(),
                'remark' => "注册礼金"
            );
            $mode = $user_id % 100;
            $this->db->insert('zjy_account_log_' . $mode, $log);
            $sql = "update zjy_account set use_money=use_money+100,reg_money=reg_money-100 where user_id={$user_id}";
            $query = $this->db->query($sql);
            return $this->db->affected_rows();
        }
    }

    /**
     * 复审
     * @param $data
     */
    function borrow_review_true($data) {
        $id = $data['id'];
        $ip = $data['ip'];

        $this->load->model('Account_model');
        $this->load->model('User_model');
        $this->load->model('Message_model');
        $this->load->model('Credit_model');
        $this->load->model('User_amount_model');

        $borrow = self::get_borrow_obj($id);
        if ($borrow['fstatus'] != 1) {
            return "此标已经审核过，不能再审核";
        }
        $repayment_account = $borrow['repayment_account'];
        $idata['account'] = $borrow['account'];
        $idata['apr'] = $borrow['apr'];
        $idata['time_limit'] = $borrow['time_limit'];
        $idata['style'] = $borrow['style'];
        $idata['is_day'] = $borrow['is_day'];
        $idata['time_limit_day'] = $borrow['time_limit_day'];
        $result = equal_interest($idata);
        $total_account = 0;
        $borrow_url = "<a href='/borrow/obj/{$id}.html' target=_blank>{$borrow['title']}</a>";
        $this->db->trans_start();
        foreach ($result as $key => $value) {
            if ($borrow['is_day'] == 1) {
                $value['repayment_time'] = time() + $borrow['time_limit_day'] * 60 * 60 * 24;
            }
            $total_account = $total_account + $value['repayment_account']; //总还金额
            $brdata['borrow_id'] = $id;
            $brdata['user_id'] = $borrow['user_id'];
            $brdata['forder'] = $key;
            $brdata['repayment_time'] = $value['repayment_time'];
            $brdata['repayment_account'] = $value['repayment_account'];
            $brdata['interest'] = $value['interest'];
            $brdata['capital'] = $value['capital'];
            $brdata['add_time'] = time();
            $brdata['addip'] = $ip;
            $this->db->insert('zjy_borrow_repayment', $brdata);
            $repayment_account = $value['repayment_account'];
        }
        //扣除所有投资者的金钱。
        $query = $this->db->query("select id,user_id,account,repayment_account,add_time,is_exp from zjy_borrow_tender where fstatus = 0 and borrow_id=$id");
        $tender_list = $query->result_array();
        $mail_tender_list = $tender_list;//实例拷贝而非指针

        foreach ($tender_list as $tender) {
            $this->db->query("update zjy_borrow_tender set fstatus=1 where id={$tender['id']}");

            $user_info = $this->User_model->get_by_uid($tender['user_id']);
            //扣除冻结金额
            $mode = $tender['user_id'] % 100;
            $user_account = $this->Account_model->get_account($tender['user_id']);
            $log['user_id'] = $user_account['user_id'];
            $log['ftype'] = INVEST; //扣除冻结款
            $log['money'] = $tender['account'];
            if($tender['is_exp'] == 1){
            	$log['money'] = $tender['account'] - $user_account['exp_money'];
            }
            $log['total'] = $user_account['total'] - $log['money'];
            $log['use_money'] = $user_account['use_money'];
            $log['no_use_money'] = $user_account['no_use_money'] - $log['money'];
            $log['collection'] = $user_account['collection'];
            $log['to_user'] = $borrow['user_id'];
            $log['remark'] = "投标成功费用扣除";
            $log['add_time'] = time();
            $log['addip'] = $ip;
            $this->db->insert('zjy_account_log_' . $mode, $log);
            $this->db->query("update zjy_account set total=total-{$log['money']},no_use_money=no_use_money-{$log['money']} where user_id={$tender['user_id']}");

            unset($user_account);
            unset($log);
            //添加待收的金额
            $user_account = $this->Account_model->get_account($tender['user_id']);
            $log['user_id'] = $user_account['user_id'];
            $log['ftype'] = COLLECTION; //待收金额
            $log['money'] = $tender['repayment_account'];
            $log['total'] = $user_account['total'] + $log['money'];
            $log['use_money'] = $user_account['use_money'];
            $log['no_use_money'] = $user_account['no_use_money'];
            $log['collection'] = $user_account['collection'] + $log['money'];
            $log['to_user'] = $borrow['user_id'];
            $log['remark'] = "待收金额";
            $log['add_time'] = time();
            $log['addip'] = $ip;
            $this->db->insert('zjy_account_log_' . $mode, $log);
            $this->db->query("update zjy_account set total=total+{$log['money']},collection=collection+{$log['money']} where user_id={$tender['user_id']}");

            //提醒设置
            $this->Message_model->send(array('sent_user' => $borrow['user_id'], 'receive_user' => $tender['user_id'],
                'name' => "投资的标[<font color=red>{$borrow['title']}</font>]满标审核成功",
                'fstatus' => 0, 'message_type' => 'system', 'sented' => 0, 'deltype' => 0,
                'content' => "你所投资的标[<a href='/borrow/obj/{$borrow['id']}.html' target=_blank><font color=red>{$borrow['title']}</font></a>]在" . date("Y-m-d", time()) . "已经审核通过",
                'add_time' => time(), 'addip' => $ip));

            //增加积分
            if ($borrow['is_day'] == 1) {
                $credit_value = round($tender['account'] / 100 * 1);
            } else {
                $credit_value = round($tender['account'] / 100 * $borrow['time_limit']);
            }

            $credit_invest_success = $this->Credit_model->get_credit_rule(array('nid' => 'invest_success'));

            $credit_log = array('user_id' => $tender['user_id'],
                'type_id' => $credit_invest_success['id'],
                'op' => 1,
                'credit_value' => $credit_value,
                'remark' => $credit_invest_success['name'] . $credit_value . '分',
                'op_user' => $borrow['user_id'],
                'add_time' => time(),
                'addip' => $ip);
            $this->Credit_model->incr_credit($credit_log);

            //更新投资人的投标标的还款日期
            $co_time = time() - $tender['add_time'];
            $sql = " update zjy_borrow_collection set repay_time=repay_time+{$co_time} where tender_id='{$tender['id']}'";
            if ($borrow['is_day'] == 1) {
                $co_time = time() + ($borrow['time_limit_day']) * 60 * 60 * 24;
                $sql = " update zjy_borrow_collection set repay_time={$co_time} where tender_id={$tender['id']}";
            }
            $this->db->query($sql);
        }

        //借款者总金额增加。
        $mode = $borrow['user_id'] % 100;
        unset($user_account);
        $user_account = $this->Account_model->get_account($borrow['user_id']);
        $borrow_log['user_id'] = $borrow['user_id'];
        $borrow_log['ftype'] = BORROW_SUCCESS;
        $borrow_log['money'] = $borrow['account'];
        $borrow_log['total'] = $user_account['total'] + $borrow_log['money'];
        $borrow_log['use_money'] = $user_account['use_money'] + $borrow_log['money'];
        $borrow_log['no_use_money'] = $user_account['no_use_money'];
        $borrow_log['collection'] = $user_account['collection'];
        $borrow_log['to_user'] = "1";
        $borrow_log['remark'] = "通过[{$borrow_url}]借到的款";
        $borrow_log['add_time'] = time();
        $borrow_log['addip'] = $ip;
        $this->db->insert('zjy_account_log_' . $mode, $borrow_log);
        $this->db->query("update zjy_account set total=total+{$borrow_log['money']},use_money=use_money+{$borrow_log['money']} where user_id={$borrow['user_id']}");


        /* if($borrow['ftype'] != 3 ){//如果是非净值标，则冻结借款保证金
          //冻结借款标的保证金10%。
          unset($user_account);
          $user_account = $this->Account_model->get_account($borrow['user_id']);
          $margin_log['user_id'] 	= $borrow['user_id'];
          $margin_log['ftype'] 	= MARGIN;
          $margin_log['money'] 	= $borrow['account']*CON_BORROW_DEPOSIT;
          if(CON_BORROW_DEPOSIT==0){//CON_BORROW_DEPOSIT等于0不用保证金
          $margin_log['money'] = 0;
          }
          $margin_log['total'] 		= $user_account['total'];
          $margin_log['use_money'] 	= $user_account['use_money']-$margin_log['money'];
          $margin_log['no_use_money'] = $user_account['no_use_money']+$margin_log['money'];
          $margin_log['collection'] 	= $user_account['collection'];
          $margin_log['to_user'] 		= "1";
          $margin_log['op'] 		= 1;
          $margin_log['remark'] 		= "冻结借款标的[{$borrow_url}]的保证金";
          $margin_log['add_time'] 	= time();
          $margin_log['addip'] 		= $ip;
          if($margin_log['money'] != 0){//如果保证金等于0，那不在写记录了
          $this->db->insert('zjy_account_log_'.$mode, $margin_log);
          $this->db->query("update zjy_account set use_money=use_money-{$margin_log['money']},no_use_money=no_use_money+{$margin_log['money']} where user_id={$borrow['user_id']}");
          $this->db->query("update zjy_borrow set forst_account={$margin_log['money']} where id={$id}");//更新保证金
          }
          } */

        //扣除0.5%的手续费
        $money = 0;
        if ($borrow['ftype'] != 5) {
            //$money = round($borrow['time_limit']*$borrow['borrow_fee']*$borrow['account'],2);
//            $money = round($borrow['time_limit'] * $borrow['borrow_fee'] * $borrow['account'] / 100, 2);
            $money = round($borrow['time_limit']*CON_BORROW_FEE*$borrow['account'],2);

            $user_account = $this->Account_model->get_account($borrow['user_id']);
            $fee_log['user_id'] = $borrow['user_id'];
            $fee_log['ftype'] = BORROW_FEE;
            $fee_log['money'] = $money;
            $fee_log['total'] = $user_account['total'] - $fee_log['money'];
            $fee_log['use_money'] = $user_account['use_money'] - $fee_log['money'];
            $fee_log['no_use_money'] = $user_account['no_use_money'];
            $fee_log['collection'] = $user_account['collection'];
            $fee_log['to_user'] = "1";
            $fee_log['op'] = 1;
            $fee_log['remark'] = "借款[{$borrow_url}]的手续费";
            $fee_log['add_time'] = time();
            $fee_log['addip'] = $ip;
            if ($fee_log['money'] != 0) {
                $this->db->insert('zjy_account_log_' . $mode, $fee_log);
                $this->db->query("update zjy_account set total=total-{$fee_log['money']},use_money=use_money-{$fee_log['money']} where user_id={$borrow['user_id']}");
            }
        }

        //更新满标时的操作人
        $nowtime = time();
        $endtime = get_times(array("num" => $borrow['time_limit'], "time" => $nowtime));
        if ($borrow['style'] == 1) {
            $_each_time = "每三个月后" . date("d", $nowtime) . "日";
        } else {
            $_each_time = "每月" . date("d", $nowtime) . "日";
        }

        if ($borrow['is_day'] == 1) {
            /* $cur_month_day = date('t');//获取当前月的天数
              $endtime	= $endtime-($cur_month_day-$borrow['time_limit_day'])*60*60*24; */
            //$endtime	= $endtime-(30-$borrow['time_limit_day'])*60*60*24;
            $endtime = time() + $borrow['time_limit_day'] * 60 * 60 * 24;
            $_each_time = date('m月d日', $endtime);
        }
        $this->db->query("update zjy_borrow set success_time={$nowtime},end_time={$endtime},each_time='{$_each_time}',payment_account={$repayment_account} where id={$id}");

        //扣除借款额度,净值标和秒标不扣除额度
        if ($borrow['ftype'] != 3 && $borrow['ftype'] != 5) {
            $user_amount = $this->User_amount_model->get_one($borrow['user_id']);
            $uamount_log['user_id'] = $borrow['user_id'];
            $uamount_log['ftype'] = AMOUNT_BORROW_SUCCESS;
            $uamount_log['amount_type'] = 1;
            $uamount_log['account'] = $borrow['account'];
            $uamount_log['account_all'] = $user_amount['credit'] - $uamount_log['account'];
            $uamount_log['account_use'] = $borrow['user_id'] - $uamount_log['account'];
            $uamount_log['account_nouse'] = $user_amount['credit_nouse'];
            $uamount_log['remark'] = "借款成功，扣除额度";
            $uamount_log['add_time'] = time();
            $uamount_log['addip'] = $ip;
            $this->db->insert('zjy_user_amount_log', $uamount_log);
            $this->db->query("update zjy_user_amount set credit_use=credit_use-{$uamount_log['account']}
								where user_id={$borrow['user_id']}");
        }

        //提醒设置
        $this->Message_model->send(array('sent_user' => 1, 'receive_user' => $borrow['user_id'],
            'name' => "招标[<font color=red>{$borrow['title']}</font>]满标审核成功",
            'fstatus' => 0, 'message_type' => 'system', 'sented' => 0, 'deltype' => 0,
            'content' => "你的借款标[<a href='/borrow/obj/{$borrow['id']}.html' target=_blank><font color=red>{$borrow['title']}</font></a>]在" . date("Y-m-d", time()) . "已经审核通过<br />成功借到{$borrow['account']}元<br />扣除手续费：{$money}元",
            'add_time' => time(), 'addip' => $ip));

        //如果有设置奖励并且招标成功，或者失败也奖励
        if ($borrow['award'] == 2 || $borrow['funds'] > 0) {
            $query = $this->db->query("select user_id,account,is_exp from zjy_borrow_tender where borrow_id=$id");
            $tender_list = $query->result_array();
            $total_money_award = 0;
            foreach ($tender_list as $tender) {
                //投标奖励扣除和增加。
                $money = round((($borrow['funds'] / 100) * $tender['account']), 2);
                unset($user_account);
                unset($log);
                $user_account = $this->Account_model->get_account($tender['user_id']);
                $log['user_id'] = $tender['user_id'];
                $log['ftype'] = AWARD_ADD;
                $log['money'] = $money;
                $log['total'] = $user_account['total'] + $money;
                $log['use_money'] = $user_account['use_money'] + $money;
                $log['no_use_money'] = $user_account['no_use_money'];
                $log['collection'] = $user_account['collection'];
                $log['to_user'] = $borrow['user_id'];
                $log['remark'] = "借款[{$borrow_url}]的奖励";
                $log['add_time'] = time();
                $log['addip'] = $ip;
                $mode = $tender['user_id'] % 100;
                $this->db->insert('zjy_account_log_' . $mode, $log);
                $this->db->query("update zjy_account set total=total+{$log['money']},use_money=use_money+{$log['money']} where user_id={$tender['user_id']}");

                //提醒设置
                $this->Message_model->send(array('sent_user' => $borrow['user_id'], 'receive_user' => $tender['user_id'],
                    'name' => "投标奖励发放",
                    'fstatus' => 0, 'message_type' => 'system', 'sented' => 0, 'deltype' => 0,
                    'content' => "您收到投标奖励" . $money,
                    'add_time' => time(), 'addip' => $ip));

                unset($user_account);
                unset($log);
                $user_account = $this->Account_model->get_account($borrow['user_id']);
                $log['user_id'] = $borrow['user_id'];
                $log['ftype'] = AWARD_LOWER;
                $log['money'] = $money;
                $log['total'] = $user_account['total'] - $money;
                $log['use_money'] = $user_account['use_money'] - $money;
                $log['no_use_money'] = $user_account['no_use_money'];
                $log['collection'] = $user_account['collection'];
                $log['to_user'] = 1;
                $log['op'] = 1;
                $log['remark'] = "扣除借款[{$borrow_url}]的奖励";
                $log['add_time'] = time();
                $log['addip'] = $ip;
                $mode = $borrow['user_id'] % 100;
                $this->db->insert('zjy_account_log_' . $mode, $log);
                $this->db->query("update zjy_account set total=total-{$log['money']},use_money=use_money-{$log['money']} where user_id={$borrow['user_id']}");

                $total_money_award += $money;
            }
            //提醒设置
            $this->Message_model->send(array('sent_user' => 1, 'receive_user' => $borrow['user_id'],
                'name' => "投标奖励发放",
                'fstatus' => 0, 'message_type' => 'system', 'sented' => 0, 'deltype' => 0,
                'content' => "您共发放到投标奖励" . $total_money_award,
                'add_time' => time(), 'addip' => $ip));
        }
        //更新满标时的操作人
        $this->db->query("update zjy_borrow set repayment_user={$data['repayment_user']},repayment_account={$total_account},repayment_remark='{$data['repayment_remark']}',repayment_time='" . time() . "',fstatus=3 where id={$id}");

        $this->db->trans_complete();
        if ($this->db->trans_status() && $borrow['ftype'] != 5) {
            /* 生成PDF格式文件  */
            $borrow_user = $this->User_model->get_by_uid($borrow['user_id']);
            if($borrow_user['email']){
                $this->load->library('/phpmailer/PHPMailer');
                $this->phpmailer->IsSMTP();
                foreach($mail_tender_list as $tender){
                    $tender_user = $this->User_model->get_by_uid($tender['user_id']);
                    $this->phpmailer->AddAddress($borrow_user['email'], $borrow_user['username']); //收件人
                    if($tender_user['email']){
                        $this->phpmailer->AddBCC($tender_user['email'], $tender_user['username']); //抄送
                    }
                    $this->load->library('func');
                    $html = $this->func->protocol_msg($id,$tender['id']);
                    $this->phpmailer->Subject = "借款标“{$borrow['title']}”的借款协议书（可到网站下载PDF格式）";
                    $this->phpmailer->Body = $html;
                    $this->phpmailer->AltBody = "This is the body in plain text for non-HTML mail clients";
                    $this->phpmailer->Send();
                }
            }

            return 1;
        } else {
            return 0;
        }
    }

    /**
     * 复审不通过
     * @param $data
     */
    function borrow_review_false($data) {
        $id = $data['id'];
        $ip = $data['ip'];
        $fstatus = $data['fstatus'];

        $this->load->model('Account_model');
        $this->load->model('Message_model');
        $borrow = self::get_borrow_obj($id);
        $borrow_url = "<a href='/borrow/obj/{$id}.html' target=_blank>{$borrow['title']}</a>";
        //返回所有投资者的金钱。
        $query = $this->db->query("select id,user_id,account,repayment_account,jiaoyan,add_time from zjy_borrow_tender where borrow_id={$id}");
        $tender_list = $query->result_array();
        $this->db->trans_start();
        foreach ($tender_list as $tender) {
            $mode = $tender['user_id'] % 100;
            $user_account = $this->Account_model->get_account($tender['user_id']);
            $log['user_id'] = $tender['user_id'];
            $log['ftype'] = INVEST_FALSE;
            $log['money'] = $tender['account'];
            $log['total'] = $user_account['total'];
            $log['use_money'] = $user_account['use_money'] + $log['money'];
            $log['no_use_money'] = $user_account['no_use_money'] - $log['money'];
            $log['collection'] = $user_account['collection'];
            $log['to_user'] = $borrow['user_id'];
            $log['remark'] = "招标[{$borrow_url}]失败返回的投标额";
            $log['add_time'] = time();
            $log['addip'] = $ip;
            $this->db->insert('zjy_account_log_' . $mode, $log);
            $this->db->query("update zjy_account set use_money=use_money+{$log['money']},no_use_money=no_use_money-{$log['money']} where user_id={$tender['user_id']}");
            if ($tender['jiaoyan'] != 1) {
                $this->db->query("update zjy_borrow_tender set jiaoyan=1 where borrow_id={$id} and id={$tender['id']}");
            }
            $this->db->query("update zjy_borrow_collection set fstatus=2 where tender_id={$tender['id']}");
            $this->db->query("update zjy_borrow_tender set fstatus=2 where id={$tender['id']}");
            //提醒设置
            $this->Message_model->send(array('sent_user' => 1, 'receive_user' => $tender['user_id'],
                'name' => "投资的标[<font color=red>{$borrow['title']}</font>]满标审核失败",
                'fstatus' => 0, 'message_type' => 'system', 'sented' => 0, 'deltype' => 0,
                'content' => "你所投资的标[<a href='/borrow/obj/{$id}.html' target=_blank><font color=red>{$borrow['title']}</font></a>]在" . date("Y-m-d", time()) . "审核失败,失败原因：{$data['repayment_remark']}",
                'add_time' => time(), 'addip' => $ip));
        }
        $this->Message_model->send(array('sent_user' => 1, 'receive_user' => $borrow['user_id'],
            'name' => "你所申请的标[<font color=red>{$borrow['title']}</font>]满标审核失败",
            'fstatus' => 0, 'message_type' => 'system', 'sented' => 0, 'deltype' => 0,
            'content' => "你所申请的标[<a href='/borrow/obj/{$data['id']}.html' target=_blank><font color=red>{$borrow['title']}</font></a>]在" . date("Y-m-d", time()) . "审核失败,失败原因：{$data['repayment_remark']}",
            'add_time' => time(), 'addip' => $ip));

        $this->db->query("update zjy_borrow set repayment_user={$data['repayment_user']},repayment_remark='{$data['repayment_remark']}',repayment_time='" . time() . "',fstatus=4 where id={$id}");
        $this->db->trans_complete();
        if ($this->db->trans_status()) {
            return 1;
        } else {
            return 0;
        }
    }

    /**
     *
     * 壹抵押、壹担保、壹理财
     */
    function get_borrow_credit_list($ftype, $limit = 6) {
        $select = "b.id,b.ftype,b.title,b.project_number,b.auto_verify_time,b.account_yes/b.account as scales,"
                . "b.auto_verify_time,b.is_mjb,b.time_limit,b.style,b.tender_times,b.fstatus,b.account,b.account_yes,b.apr,"
                . "b.lowest_account,b.most_account,b.valid_time,b.award,b.funds,b.is_day,b.time_limit_day,b.guarantee_id,"
                . "b.repayment_yesaccount,b.repayment_account,b.end_time,b.thumbnail,g.name, b.verify_time, b.auto_verify_time ";

        $sql = "select {$select} from zjy_borrow  as b left join zjy_borrow_guarantee as g on b.guarantee_id = g.id where b.ftype=$ftype and b.fstatus in(0,1,3) and is_check=1 ";

        $sql .= " order by scales asc,fstatus asc,id desc limit $limit";
        $query = $this->db->query($sql);
        $list = $query->result_array();
        if ($list) {
            return $list;
        }
    }

    function get_borrow_recommend() {
        $select = "b.id,b.ftype,b.title,b.is_mjb,b.project_number,b.auto_verify_time,b.time_limit,b.style,"
                . "b.tender_times,b.fstatus,b.account,b.account_yes,b.apr,b.lowest_account,b.most_account,"
                . "b.valid_time,b.award,b.funds,b.is_day,b.time_limit_day,b.guarantee_id,b.repayment_yesaccount,"
                . "b.repayment_account,b.end_time,b.thumbnail,g.name, b.verify_time, b.auto_verify_time ";

        $sql = "select {$select} from zjy_borrow  as b left join zjy_borrow_guarantee as g on b.guarantee_id = g.id where b.fstatus in(0,1,3) and is_check=1 and recommend_id=1";

        $sql .= " order by fstatus asc,id desc limit 1";
        $query = $this->db->query($sql);
        $list = $query->row_array();
        return $list;
    }

    /**
     * 查询
     * @param $data
     */
    function get_borrow_list($data) {
        //封装查询内容

        $select = "*";
        if ($data['select'] == 1) {
            $select = " id, user_id, title, account, apr, funds, time_limit ,
						style, is_dxb, account_yes/account as scales, summary, business,
						fstatus, ftype, award, is_day, time_limit_day, verify_time,is_kjb,
						account_yes, valid_time, end_time, lowest_account,most_account,
						repayment_account,repayment_yesaccount,lz_endtime,title_img,tender_times,thumbnail,add_time,open_time";
        } elseif ($data['select'] == 2) {
            $select = "user_id,id,title,verify_time, summary, business,repayment_time,fstatus,account_yes/account as scales";
        }

        //封装条件
        $_where = " where 1=1 ";
        if (isset($data['where']['is_index']) && $data['where']['is_index'] == 1 && !isset($data['where']['is_yjb'])) {
            $_where .= " and ftype != 6";
        }
        if (isset($data['where']['is_yjb']) && $data['where']['is_yjb'] == 1) {
            //$_where .= " and ftype = 6 and account<account_yes";
            $_where .= " and ftype = 6";
        }
        if (isset($data['where']['is_index']) && $data['where']['is_index'] == 1 && !isset($data['where']['is_kjb'])) {
            $_where .= " and is_kjb = 0";
        }
        if (isset($data['where']['is_kjb']) && $data['where']['is_kjb'] == 1) {
            $_where .= " and is_kjb = 1";
        }
        if (isset($data['where']['is_mjb']) && $data['where']['is_mjb'] == 0) {
            $_where .= " and is_mjb = 0";
        }
        if (isset($data['where']['is_mjb']) && $data['where']['is_mjb'] == 1) {
            $_where .= " and is_mjb = 1";
        }
        if (isset($data['where']['keywords']) && $data['where']['keywords'] != '') {
            $_where .= " and title like '%" . $data['where']['keywords'] . "%'";
        }
        if (isset($data['where']['time_limit']) && $data['where']['time_limit'] > 0) {
            $_where .= " and time_limit = " . $data['where']['time_limit'];
        }
        if (isset($data['where']['user_id']) && $data['where']['user_id'] != '') {
            $_where .= " and user_id = " . $data['where']['user_id'];
        }
        if (isset($data['where']['fstatus']) && $data['where']['fstatus'] != '') {
            $_where .= " and fstatus = " . $data['where']['fstatus'];
        } else {
            $_where .= " and (fstatus = 1 or fstatus = 3)";
        }
        //为了前台只显示可投资的标
        $current_time = time();
        if(isset($data['where']['ketou']) && $data['where']['ketou'] == 1) {
            $_where .= " and account_yes < account";
        }
        if (isset($data['where']['qtype']) && $data['where']['qtype'] != '') {
            $now_times = time();
            if ($data['where']['qtype'] == 'index') {
                $_where .= " and (ftype!=4 and fstatus=1) or (ftype=4 and account>account_yes and lz_endtime>$now_times and fstatus in (1,3))";
            } elseif ($data['where']['qtype'] == 'now') {
                $_where .= " and repayment_account != repayment_yesaccount and fstatus=3";
            } elseif ($data['where']['qtype'] == 'yes') {
                $_where .= " and repayment_account = repayment_yesaccount and fstatus=3 ";
            } elseif ($data['where']['qtype'] == 'late') {
                $_where .= " and ftype!=4 and repayment_account != repayment_yesaccount and
							 fstatus=3 and end_time<" . (time() + 12 * 60 * 60);
            }
        } else {
            if (isset($data['where']['is_kjb']) && $data['where']['is_kjb'] == 1) {
                $_where .= " and fstatus in (1)";
            } elseif (isset($data['where']['is_yjb']) && $data['where']['is_yjb'] == 1) {
                $_where .= " and fstatus in (1,3)";
            } else {
                $_where .= " and (fstatus=1 or (ftype!=4 and fstatus=3 and repayment_account!=repayment_yesaccount)
						or ((ftype=4 or ftype=5) and fstatus in (1,3) and (lz_endtime>UNIX_TIMESTAMP() or lz_endtime=0)))";
            }
        }
        if (isset($data['where']['ftype']) && $data['where']['ftype'] > 0) {
            $_where .= " and ftype = " . $data['where']['ftype'];
        }



        //排序
        $_order = " order by scales asc,fstatus asc,id desc ";
        if (isset($data['where']['order']) && $data['where']['order'] == 'index') {
            $_order = " order by scales asc,fstatus asc,verify_time desc,id desc ";
        }
        if (isset($data['where']['order']) && $data['where']['order'] == 'yjb') {
            $_order = " order by id desc";
        }
        if (isset($data['where']['qtype']) && $data['where']['qtype'] == 'now') {
            $_order = " order by id desc ";
        }
        //封装sql
        $page_size = $data['page_size'];
        $page_start = $data['page_start'];
        $sql_result = "select $select from zjy_borrow";
        $sql_result .= $_where;
        $sql_result .= $_order;
        $sql_result .= " limit $page_start, $page_size"; //echo $sql_result;exit;
        $query = $this->db->query($sql_result);
        if (isset($data['list']) && $data['list'] == 1) {
            return $query->result_array();
        }
        $data['borrow_list'] = $query->result_array();

        //总记录条数
        $sql_count = "select count(*) as count from zjy_borrow";
        $sql_count .= $_where;
        $query = $this->db->query($sql_count);
        $data['borrow_count'] = $query->row()->count;
        return $data;
    }

    function get_borrow_blist($data) {
        //封装查询内容

        $select = "*";
        if ($data['select'] == 1) {
            $select = " id, user_id, title, account, apr, funds, time_limit ,
						style, account_yes/account as scales, summary, business,is_kjb,
						fstatus, ftype, award, is_day, time_limit_day, verify_time,
						account_yes, valid_time, end_time, lowest_account, valid_time,
						repayment_account,repayment_yesaccount,lz_endtime,title_img,auto_verify_time,tender_times,recommend_id,thumbnail,project_number,guarantee_id,is_mjb";
        }

        //封装条件
        $ctime = time();

        if (isset($data['where']['srate'])) {
            $_where = ' where 1=1 ';
            if ($data['where']['srate'] == 1) {
                $_where .= " and fstatus = 0 and is_check = 1 ";
            } elseif ($data['where']['srate'] == 2) {
                $_where .= " and fstatus = 1";
            } elseif ($data['where']['srate'] == 3) {
                $_where .= " and fstatus = 3 and account = account_yes ";
            } else {
                $_where .= " and (fstatus in(1,3) or (fstatus =0 and is_check =1) )";
            }
        } else {
            $_where = " where (fstatus in(1,3) or (fstatus =0 and is_check =1) )";
        }

        if (isset($data['where']['time_limit']) && $data['where']['time_limit'] > 0) {
            $_where .= " and time_limit = " . $data['where']['time_limit'];
        }
        if (isset($data['where']['ftype']) && $data['where']['ftype'] > 0) {
            $_where .= " and ftype = " . $data['where']['ftype'];
        }


        if (isset($data['where']['sftype']) && $data['where']['sftype'] > 0) {
            $_where .= " and ftype = " . $data['where']['sftype'];
        }

        if (isset($data['where']['saccount'])) {
            if ($data['where']['saccount'] == 1) {
                $_where .= " and account<100000";
            } elseif ($data['where']['saccount'] == 2) {
                $_where .= " and account>=100000 and account<200000";
            } elseif ($data['where']['saccount'] == 3) {
                $_where .= " and account>=200000 and account<500000";
            } elseif ($data['where']['saccount'] == 4) {
                $_where .= " and account>=500000";
            }
        }
        if (isset($data['where']['sapr'])) {
            if ($data['where']['sapr'] == 1) {
                $_where .= " and apr<10 ";
            } elseif ($data['where']['sapr'] == 2) {
                $_where .= " and apr>=10 and apr<13 ";
            } elseif ($data['where']['sapr'] == 3) {
                $_where .= " and apr>=13 and apr<15 ";
            } elseif ($data['where']['sapr'] == 4) {
                $_where .= " and apr>=15 ";
            }
        }

        if (isset($data['where']['slimit'])) {
            if ($data['where']['slimit'] == 1) {
                $_where .= " and is_day=0 and time_limit<2";
            } elseif ($data['where']['slimit'] == 2) {
                $_where .= " and is_day=0 and time_limit>=2 and time_limit<6";
            } elseif ($data['where']['slimit'] == 3) {
                $_where .= " and is_day=0 and time_limit>=6 and time_limit<12";
            } elseif ($data['where']['slimit'] == 4) {
                $_where .= " and is_day=0 and time_limit>=12";
            }
        }
        //verify_time
        //$vtime = time()-3600*24*5;
        //$_where .= " and verify_time>".$vtime;
        //排序
        if (isset($data['where']['sorder'])) {
            if ($data['where']['sorder'] == "formal_down") {
                $_order = " order by verify_time desc";
            } elseif ($data['where']['sorder'] == "formal_up") {
                $_order = " order by verify_time asc";
            } elseif ($data['where']['sorder'] == "account_down") {
                $_order = " order by account asc";
            } elseif ($data['where']['sorder'] == "account_up") {
                $_order = " order by account desc";
            } elseif ($data['where']['sorder'] == "apr_down") {
                $_order = " order by apr asc";
            } elseif ($data['where']['sorder'] == "apr_up") {
                $_order = " order by apr desc";
            } elseif ($data['where']['sorder'] == "repaytime_down") {
                $_order = " order by each_time desc";
            } elseif ($data['where']['sorder'] == "repaytime_up") {
                $_order = " order by each_time asc";
            }
        } else {
            $_order = " order by scales asc,fstatus asc,id desc ";
        }

        if (isset($data['where']['qtype']) && $data['where']['qtype'] == 'now') {
            $_order = " order by id desc ";
        }
        //封装sql
        $page_size = $data['page_size'];
        $page_start = $data['page_start'];
        $sql_result = "select $select from zjy_borrow";
        $sql_result .= $_where;
        $sql_result .= $_order;
        $sql_result .= " limit $page_start, $page_size";
        $query = $this->db->query($sql_result);
        if (isset($data['list']) && $data['list'] == 1) {
            return $query->result_array();
        }
        $data['borrow_list'] = $query->result_array();

        //总记录条数
        $sql_count = "select count(*) as count from zjy_borrow";
        $sql_count .= $_where;
        $query = $this->db->query($sql_count);
        $data['borrow_count'] = $query->row()->count;
        return $data;
    }

    //逾期还款列表
    function get_late_list($data = array()) {
        $select = "p1.id,p1.user_id,p1.repayment_time,p1.capital,p1.late_days,p1.late_interest,p1.repayment_account,
					p2.realname,p2.phone,p2.email,p2.qq,p2.sex,p2.card_id,p2.province,p2.city,p2.area";
        //封装条件
        if (isset($data['where']['late_day']) && $data['where']['late_day'] != '') {
            $_repayment_time = time() - 60 * 60 * 24 * $data['late_day'];
        } else {
            $_repayment_time = time();
        }
        $_where = " where p1.repayment_time < " . time() . " and p1.fstatus!=1 and p1.borrow_id>0";
        //排序
        $_order = " order by p1.id desc ";

        //封装sql
        $sql_result = "select $select from zjy_borrow_repayment as p1 left join zjy_user as p2 on p1.user_id=p2.user_id ";
        $sql_result .= $_where;
        $sql_result .= $_order;
        $query = $this->db->query($sql_result);

        if (isset($data['list']) && $data['list'] == 1) {
            return $query->result_array();
        }
        $late_list1 = $query->result_array();
        $late_list = array();
        foreach ($late_list1 as $key => $value) {
            $late = late_interest($value['repayment_time'], $value['capital']);
            $late_list[$value['user_id']]['realname'] = $value['realname'];
            $late_list[$value['user_id']]['phone'] = $value['phone'];
            $late_list[$value['user_id']]['user_id'] = $value['user_id'];
            $late_list[$value['user_id']]['email'] = $value['email'];
            $late_list[$value['user_id']]['qq'] = $value['qq'];
            $late_list[$value['user_id']]['sex'] = $value['sex'];
            $late_list[$value['user_id']]['card_id'] = $value['card_id'];
            $late_list[$value['user_id']]['province'] = $value['province'];
            $late_list[$value['user_id']]['city'] = $value['city'];
            $late_list[$value['user_id']]['area'] = $value['area'];
            $late_list[$value['user_id']]['late_days'] = $late['late_days']; //总逾期天数
            if (@$late_list[$value['user_id']]['late_numdays'] < $late['late_days']) {
                $late_list[$value['user_id']]['late_numdays'] = $late['late_days'];
            }
            @$late_list[$value['user_id']]['late_interest'] += round($late['late_interest'] / 2, 2);
            @$late_list[$value['user_id']]['late_account'] += $value['repayment_account']; //逾期总金额
            @$late_list[$value['user_id']]['late_num'] ++; //逾期笔数
            @$late_list[$value['user_id']]['late_webnum'] = 0; //逾期笔数
        }

        $data['late_list'] = $late_list;
        //总记录条数
        $data['late_count'] = count($late_list);
        return $data;
    }

    /**
     * 查询
     * @param $data
     */
    function admin_get_borrow_list($data) {
        //封装查询内容
        $select = "*";
        if ($data['select'] == 1) {
            $select = "t1.id, t1.user_id, t1.title, t1.account , t1.apr, t1.funds, t1.time_limit , t1.style,
						t1.fstatus, t1.ftype, t1.award, t1.verify_time, t1.account_yes, t1.valid_time ";
        }

        //封装条件
        $_where = " where 1=1 ";
        if (isset($data['where']['title']) && $data['where']['title'] != '') {
            $_where .= " and t1.title like '%" . $data['where']['title'] . "%'";
        }
        if (isset($data['where']['fstatus']) && $data['where']['fstatus'] != '') {
            $_where .= " and t1.fstatus = " . $data['where']['fstatus'];
        }
        if (isset($data['where']['qtype']) && $data['where']['qtype'] == 'full') {
            $_where .= " and t1.account = t1.account_yes and t1.fstatus=1 ";
        }
        if (isset($data['where']['ftype']) && $data['where']['ftype'] != '') {
            $_where .= " and t1.ftype = " . $data['where']['ftype'];
        }

        //排序
        $order = " order by t1.id desc ";
        if (isset($data['where'])) {
            if ($data['order'] == 'verify') {
                $order = " order by t1.verify_time desc,t1.id desc ";
            }
        }


        //封装sql
        $page_size = $data['page_size'];
        $page_start = $data['page_start'];
        $sql_result = "select $select from zjy_borrow as t1 ";
        $sql_result .= $_where;
        $sql_result .= $order;
        $sql_result .= " limit $page_start, $page_size";
        $query = $this->db->query($sql_result);
        $data['borrow_list'] = $query->result_array();

        //总记录条数
        $sql_count = "select count(*) as count from zjy_borrow as t1 ";
        $sql_count .= $_where;
        $query = $this->db->query($sql_count);
        $data['borrow_count'] = $query->row()->count;
        return $data;
    }

    /**
     * 查询
     * @param $data
     */
    function get_borrow_user_list($data) {
        //封装查询内容
        $select = "*";
        if ($data['select'] == 1) {
            $select = "id, t1.user_id, username, title, account , apr, funds, time_limit ,
						is_day, time_limit_day, style, is_mjb,
						t1.fstatus, t1.ftype, t1.add_time, t1.verify_time, t1.account_yes, t1.lowest_account, t1.most_account,is_check";
        }

        //封装条件
        $_where = " where 1=1 ";
        if (isset($data['where']['user_id']) && $data['where']['user_id'] != '') {
            $_where .= " and t1.user_id =" . $data['where']['user_id'] ;
        }
        if (isset($data['where']['title']) && $data['where']['title'] != '') {
            $_where .= " and title like '%" . $data['where']['title'] . "%'";
        }
        if (isset($data['where']['fstatus']) && $data['where']['fstatus'] != '') {
            $_where .= " and t1.fstatus = " . $data['where']['fstatus'];
        }
        if (isset($data['where']['qtype']) && $data['where']['qtype'] == 'full') {
            $_where .= " and t1.account = t1.account_yes and t1.fstatus=1 ";
        }
        if (isset($data['where']['ftype']) && $data['where']['ftype'] != '') {
            $_where .= " and ftype = " . $data['where']['ftype'];
        }
        if (isset($data['where']['username']) && $data['where']['username'] != '') {
            $_where .= " and t2.username like '%" . $data['where']['username'] . "%'";
        }

        if (isset($data['where']['auto_verify_time']) && $data['where']['auto_verify_time'] > 0) {
            $_where .= " and t1.auto_verify_time = " . $data['where']['auto_verify_time'];
        }

        if (isset($data['where']['is_check']) && $data['where']['is_check'] > 0) {
            $_where .= " and t1.is_check = " . $data['where']['is_check'];
        }

        //排序
        $order = " order by t1.id desc ";
        //封装sql
        $page_size = $data['page_size'];
        $page_start = $data['page_start'];
        $sql_result = "select $select from zjy_borrow as t1 left join zjy_user as t2 on t1.user_id=t2.user_id ";
        $sql_result .= $_where;
        $sql_result .= $order;
        $sql_result .= " limit $page_start, $page_size";
        $query = $this->db->query($sql_result);
        $data['borrow_list'] = $query->result_array();

        //总记录条数
        $sql_count = "select count(*) as count from zjy_borrow as t1 left join zjy_user as t2 on t1.user_id=t2.user_id ";
        $sql_count .= $_where;
        $query = $this->db->query($sql_count);
        $data['borrow_count'] = $query->row()->count;
        return $data;
    }
    //后台首页 初审和复审的标
    function first_total($where) {
    	if($where == 'fstaus') $_where = ' where t1.fstatus = 0';
    	else if($where == 'qtype') $_where = " where t1.account = t1.account_yes and t1.fstatus=1 "; 	
    	$sql_count = "select count(id) as count from zjy_borrow as t1 left join zjy_user as t2 on t1.user_id=t2.user_id ";
    	$sql_count .=$_where;
    	$query = $this->db->query($sql_count);
    	return $query->row()->count;
    }

    function get_repayment_list($data) {
        //封装查询内容
        $select = "*";
        if (isset($data['select']) && $data['select'] == 1) {
            $select = " t1.id, t1.user_id, t1.fstatus, t1.forder, t1.borrow_id, t1.repayment_time, t1.repayment_yestime,
						t1.repayment_account, t1.repayment_yesaccount, t1.interest, t1.capital, t1.late_days,
						t1.late_interest, t2.id as borrow_id, t2.title, t2.ftype, t2.time_limit, t2.is_day, t2.time_limit_day, t2.apr";
        }

        //封装条件
        $_where = " where 1=1 ";
        if (isset($data['where']['borrow_id']) && $data['where']['borrow_id'] != '') {
            $_where .= " and t1.borrow_id = " . $data['where']['borrow_id'];
        }
        if (isset($data['where']['title']) && $data['where']['title'] != '') {
            $_where .= " and t2.title like '%" . $data['where']['title'] . "%'";
        }
        if (isset($data['where']['fstatus']) && $data['where']['fstatus'] == 0) {
            $_where .= " and t1.fstatus = 0";
        } elseif (isset($data['where']['fstatus']) && $data['where']['fstatus'] == -2) {
            $_where .= " and t1.fstatus in (0,1)";
        } elseif (isset($data['where']['fstatus']) && $data['where']['fstatus'] != -1) {
            $_where .= " and t1.fstatus = " . $data['where']['fstatus'];
        }
        if (isset($data['where']['username']) && $data['where']['username'] != '') {
            $_where .= " and t3.username like '%" . $data['where']['username'] . "%'";
        }
        if (isset($data['where']['user_id']) && $data['where']['user_id'] != '') {
            $_where .= " and t1.user_id = " . $data['where']['user_id'];
        }
        if ($data['where']['fstatus'] == 0) {
            if (isset($data['where']['strtime']) && $data['where']['strtime'] != 0) {
                $strtime = strtotime($data['where']['strtime'] . ' 00:00:00');
                $_where .= " and t1.repayment_time >= " . $strtime;
            }
            if (isset($data['where']['endtime']) && $data['where']['endtime'] != 0) {
                $endtime = strtotime($data['where']['endtime'] . ' 23:59:59');
                $_where .= " and t1.repayment_time <= " . $endtime;
            }
        } elseif ($data['where']['fstatus'] == 1) {
            if (isset($data['where']['strtime']) && $data['where']['strtime'] != 0) {
                $strtime = strtotime($data['where']['strtime'] . ' 00:00:00');
                $_where .= " and t1.repayment_yestime >= " . $strtime;
            }
            if (isset($data['where']['endtime']) && $data['where']['endtime'] != 0) {
                $endtime = strtotime($data['where']['endtime'] . ' 23:59:59');
                $_where .= " and t1.repayment_yestime <= " . $endtime;
            }
        }


        //排序
        $order = " order by t1.repayment_time asc ";
        if (isset($data['order']) && $data['order'] == 'desc') {
            $order = " order by t1.repayment_time desc ";
        }
        //封装sql
        if (isset($data['page_size'])) {
            $page_size = $data['page_size'];
        }
        if (isset($data['page_start'])) {
            $page_start = $data['page_start'];
        }
        $sql_result = "select $select from zjy_borrow_repayment as t1 left join zjy_borrow as t2 on t1.borrow_id=t2.id";
        $sql_result .= $_where;
        $sql_result .= $order;
		
        if (isset($data['page_size'])) {
            $sql_result .= " limit $page_start, $page_size";
        }
        $query = $this->db->query($sql_result);
        $data['repayment_list'] = $query->result_array();

        //总记录条数
        $sql_count = "select count(*) as count from zjy_borrow_repayment as t1 left join zjy_borrow as t2 on t1.borrow_id=t2.id";
        $sql_count .= $_where;
        $query = $this->db->query($sql_count);
        $data['repayment_count'] = $query->row()->count;
        return $data;
    }

    function get_repayment_lz_borrow($user_id) {
        $sql = "select id,title,time_limit,account_yes,lz_endtime from zjy_borrow WHERE user_id={$user_id} AND ftype=4 AND fstatus=3 AND account_yes>0 ORDER BY id DESC";
        $query = $this->db->query($sql);
        return $query->result_array();
    }

    /**
     * 根据标和期数获取马甲应收
     * Enter description here ...
     * @param unknown_type $data
     */
    function get_borrow_collection_majia($data) {
        $borrow_id = $data['borrow_id'];
        $forder = $data['forder'];
        $fstatus = $data['fstatus']?$data['fstatus']:0;
        $_where = '';

        if ($fstatus != -1) {
            $_where .= " and fstatus = " . $fstatus;
        }

        if ($fstatus == 0) {
            if (isset($data['strtime']) && $data['strtime'] != 0) {
                $strtime = strtotime($data['strtime'] . ' 00:00:00');
                $_where .= " and repay_time >= " . $strtime;
            }
            if (isset($data['endtime']) && $data['endtime'] != 0) {
                $endtime = strtotime($data['endtime'] . ' 23:59:59');
                $_where .= " and repay_time <= " . $endtime;
            }
        } elseif ($fstatus == 1) {
            if (isset($data['strtime']) && $data['strtime'] != 0) {
                $strtime = strtotime($data['strtime'] . ' 00:00:00');
                $_where .= " and repay_yestime >= " . $strtime;
            }
            if (isset($data['endtime']) && $data['endtime'] != 0) {
                $endtime = strtotime($data['endtime'] . ' 23:59:59');
                $_where .= " and repay_yestime <= " . $endtime;
            }
        }

        $sql = "select sum(repay_account) as total_repay_account from zjy_borrow_collection WHERE
				forder={$forder} AND borrow_id={$borrow_id} {$_where} and user_id in (select user_id from zjy_user where is_self=1)";


        $query = $this->db->query($sql);
        $ret = $query->result_array();
        return $query->row()->total_repay_account;
    }

    /**
     * 查看投标的信息
     * @param Array $data
     * @return Array
     */
    function get_lz_repayment_list($data = array()) {
        //封装查询内容
        $select = "*";
        if (isset($data['select']) && $data['select'] == 1) {
            $select = " t1.id, t1.user_id, t1.fstatus, t1.forder, t1.borrow_id, t1.repay_time as repayment_time,
					    t1.repay_yestime as repayment_yestime,
						t1.repay_account as repayment_account, t1.repay_yesaccount as repayment_yesaccount,
						t1.interest, t1.capital, t1.late_days,
						t1.late_interest, t2.id as borrow_id,
						t2.title, t2.ftype, t2.time_limit, t2.apr, t2.is_day, t2.time_limit_day ";
        }

        //封装条件
        $_where = " where 1=1 and t2.fstatus=3 and ftype=4 ";
        if (isset($data['where']['ftype']) && $data['where']['ftype'] != '') {
            $_where .= " and t2.ftype = " . $data['where']['ftype'];
        }
        if (isset($data['where']['borrow_id']) && $data['where']['borrow_id'] != '') {
            $_where .= " and t1.borrow_id = " . $data['where']['borrow_id'];
        }
        if ($data['where']['fstatus'] != -1) {
            $_where .= " and t1.fstatus = " . $data['where']['fstatus'];
        }
        if (isset($data['where']['user_id']) && $data['where']['user_id'] != '') {
            $_where .= " and t2.user_id = " . $data['where']['user_id'];
        }
        if ($data['where']['fstatus'] == 0) {
            if (isset($data['where']['strtime']) && $data['where']['strtime'] != 0) {
                $strtime = strtotime($data['where']['strtime'] . ' 00:00:00');
                $_where .= " and t1.repay_time >= " . $strtime;
            }
            if (isset($data['where']['endtime']) && $data['where']['endtime'] != 0) {
                $endtime = strtotime($data['where']['endtime'] . ' 23:59:59');
                $_where .= " and t1.repay_time <= " . $endtime;
            }
        } elseif ($data['where']['fstatus'] === 1) {
            if (isset($data['where']['strtime']) && $data['where']['strtime'] != 0) {
                $strtime = strtotime($data['where']['strtime'] . ' 00:00:00');
                $_where .= " and t1.repay_yestime >= " . $strtime;
            }
            if (isset($data['where']['endtime']) && $data['where']['endtime'] != 0) {
                $endtime = strtotime($data['where']['endtime'] . ' 23:59:59');
                $_where .= " and t1.repay_yestime <= " . $endtime;
            }
        }

        //排序
        $order = " order by t1.id asc ";
        if (isset($data['order']) && $data['order'] == 'desc') {
            $order = " order by t1.id desc ";
        }
        if (isset($data['order']) && $data['order'] == '1') {
            $order = " order by t1.repay_time asc ";
        }
        //封装sql
        if (isset($data['page_size'])) {
            $page_size = $data['page_size'];
        }
        if (isset($data['page_start'])) {
            $page_start = $data['page_start'];
        }
        $sql_result = "select $select from zjy_borrow_collection as t1 left join zjy_borrow as t2 on t1.borrow_id=t2.id";
        $sql_result .= $_where;
        $sql_result .= $order;
        if (isset($data['page_size'])) {
            $sql_result .= " limit $page_start, $page_size";
        }
        $query = $this->db->query($sql_result);
        $data['repayment_list'] = $query->result_array();

        //总记录条数
        $sql_count = "select count(*) as count from zjy_borrow_collection as t1 left join zjy_borrow as t2 on t1.borrow_id=t2.id";
        $sql_count .= $_where;
        $query = $this->db->query($sql_count);
        $data['repayment_count'] = $query->row()->count;
        return $data;
    }

    /**
     * 流转标还款列表汇总
     * @param Array $data
     * @return Array
     */
    function get_lz_repayment_huizong_list($data = array()) {
        //封装查询内容
        $select = "*";
        if (isset($data['select']) && $data['select'] == 1) {
            $select = "t1.id,t1.title,t1.time_limit,t2.forder,SUM(t2.repay_account) as repay_accounts,t2.repay_time ";
        }

        //封装条件
        $_where = " where 1=1 and t1.fstatus=3 and t1.ftype in(4,6) ";
        if ($data['where']['fstatus'] != -1) {
            $_where .= " and t2.fstatus = " . $data['where']['fstatus'];
        }
        if (isset($data['where']['title']) && $data['where']['title'] != '') {
            $_where .= " and t1.title = '{$data['where']['title']}'";
        }
        if ($data['where']['fstatus'] == 0) {
            if (isset($data['where']['strtime']) && $data['where']['strtime'] != 0) {
                $strtime = strtotime($data['where']['strtime'] . ' 00:00:00');
                $_where .= " and t2.repay_time >= " . $strtime;
            }
            if (isset($data['where']['endtime']) && $data['where']['endtime'] != 0) {
                $endtime = strtotime($data['where']['endtime'] . ' 23:59:59');
                $_where .= " and t2.repay_time <= " . $endtime;
            }
            $order = " order by t2.repay_time asc ";
        } elseif ($data['where']['fstatus'] == 1) {
            if (isset($data['where']['strtime']) && $data['where']['strtime'] != 0) {
                $strtime = strtotime($data['where']['strtime'] . ' 00:00:00');
                $_where .= " and t2.repay_yestime >= " . $strtime;
            }
            if (isset($data['where']['endtime']) && $data['where']['endtime'] != 0) {
                $endtime = strtotime($data['where']['endtime'] . ' 23:59:59');
                $_where .= " and t2.repay_yestime <= " . $endtime;
            }
            $order = " order by t2.repay_yestime desc ";
        }

        //排序
        $group = " GROUP BY t2.borrow_id ";
        //$order  = " order by t2.repay_time asc ";
        //封装sql

        $sql_result = "select $select from zjy_borrow AS t1 LEFT JOIN zjy_borrow_collection AS t2 ON t1.id=t2.borrow_id";
        $sql_result .= $_where;
        $sql_result .= $group;
        $sql_result .= $order;

        if (isset($data['limit']) && $data['limit'] == 'all') {
            $query = $this->db->query($sql_result);
            $data['repayment_list'] = $query->result_array();
        } else {
            if (isset($data['page_size'])) {
                $page_size = $data['page_size'];
            }
            if (isset($data['page_start'])) {
                $page_start = $data['page_start'];
            }
            $sql_result .= " limit $page_start, $page_size";
            $query = $this->db->query($sql_result);
            $data['repayment_list'] = $query->result_array();
        }



        //总记录条数
        $sql_count = "select count(DISTINCT(t2.borrow_id)) as count from zjy_borrow AS t1 LEFT JOIN zjy_borrow_collection AS t2 ON t1.id=t2.borrow_id";
        $sql_count .= $_where;
        $query = $this->db->query($sql_count);
        $data['repayment_count'] = $query->row()->count;
        //总还款金额
        $sql_sum = "select sum(t2.repay_account) as totalmoney from zjy_borrow AS t1 LEFT JOIN zjy_borrow_collection AS t2 ON t1.id=t2.borrow_id";
        $sql_sum .= $_where;
        $query = $this->db->query($sql_sum);
        $data['totalmoney'] = $query->row()->totalmoney;
        //真实还款金额
        $_where .= " and u.is_self=0 ";
        $sql_sum = "select sum(t2.repay_account) as realmoney from zjy_borrow AS t1 LEFT JOIN zjy_borrow_collection AS t2 ON t1.id=t2.borrow_id left join zjy_user as u on t2.user_id=u.user_id";
        $sql_sum .= $_where;
        $query = $this->db->query($sql_sum);
        $data['realmoney'] = $query->row()->realmoney;

        return $data;
    }

    /**
     * 用户自动投标列表
     * @param $data
     */
    function get_borrow_auto_list($data) {
        //封装查询内容
        $select = "*";
        if (isset($data['select']) && $data['select'] == 1) {
            $select = " t1.id, t1.user_id, t1.fstatus, t1.tender_type, t1.tender_account, t1.tender_account1,
						t1.tender_scale, t1.borrow_style_status,t1.borrow_style, t1.timelimit_status, t1.timelimit_month_first,
						t1.timelimit_month_last, t1.apr_status, t1.apr_first, t1.apr_last, t1.award_status,
						t1.award_first, t1.award_last, t1.add_time, t1.borrowcount ";
        }

        //封装条件
        $_where = " where is_del=0 ";
        if (isset($data['where']['user_id']) && $data['where']['user_id'] != '') {
            $_where .= " and t1.user_id = " . $data['where']['user_id'];
        }

        //排序
        $order = " order by t1.id desc ";


        //封装sql
        $sql_result = "select $select from zjy_borrow_auto as t1 ";
        $sql_result .= $_where;
        $sql_result .= $order;
        $query = $this->db->query($sql_result);
        $data['borrow_auto_list'] = $query->result_array();
        return $data;
    }

    /**
     * 查询
     * @param $data
     */
    function get_borrow_auto_obj($id, $data = array()) {
        $select = "*";
        $this->db->select($select);
        $this->db->where('id', $id);
        $this->db->where('user_id', $data['user_id']);
        $query = $this->db->get('zjy_borrow_auto');
        return $query->row_array();
    }

    /**
     * 删除标
     * @param $data
     */
    function delete_borrow_auto($data = array()) {
        $this->db->where($data);
        $this->db->update('zjy_borrow_auto', array('is_del' => 1));
        $key = 'auto_tender_count';
        $this->mycache->delete($key);
        return $this->db->affected_rows();
    }

    function update_borrow_auto($id, $data) {
        $this->db->where('id', $id);
        $this->db->update('zjy_borrow_auto', $data);
        $key = 'auto_tender_count';
        $this->mycache->delete($key);
        return $this->db->affected_rows();
    }

    /**
     * 自动投标
     * @param $borrow_id
     */
    function auto_tender_borrow($borrow_id) {
        /* $auto_sql = "SELECT t1.id,t1.user_id,t1.tender_type,t1.tender_account,t1.tender_account1,t1.tender_scale,
          t1.borrow_style_status,t1.borrow_style,t1.timelimit_status,t1.timelimit_month_first,
          t1.timelimit_month_last,t1.apr_status,t1.apr_first,t1.apr_last,t1.award_status,
          t1.award_first,t1.award_last
          FROM zjy_borrow_auto t1,zjy_account t2 WHERE
          t1.fstatus=1 AND t1.user_id = t2.user_id AND t2.use_money >= 50 and t1.is_del=0
          GROUP BY t1.user_id ORDER BY t1.id"; */


        //默认为48小时内有效，48小时后按照新规则重新设置。
        $valid = strtotime('2014-04-17 10:00:00') + 2 * 3600 * 24;
        $now = time();
        $auto_sql = "SELECT t1.id,t1.user_id,t1.tender_type,t1.tender_account,t1.tender_account1,t1.tender_scale,
					 t1.borrow_style_status,t1.borrow_style,t1.timelimit_status,t1.timelimit_month_first,
					 t1.timelimit_month_last,t1.apr_status,t1.apr_first,t1.apr_last,t1.award_status,
					 t1.award_first,t1.award_last,t1.tender_count
					 FROM zjy_borrow_auto t1
					 left join zjy_account t2 on t1.user_id=t2.user_id
					 left join zjy_user u on t1.user_id = u.user_id
					 left join zjy_user_vip v on t1.user_id = v.user_id
					 where t1.fstatus=1  AND t2.use_money >= 50 and t1.is_del=0";

        if ($now > $valid) {
            $auto_sql .= " and t1.valid_start_time<{$now} and t1.valid_end_time>{$now}";
        }

        $auto_sql .= " GROUP BY t1.user_id  ORDER BY t1.valid_start_time DESC,t1.valid_end_time DESC,v.vip_status DESC,t1.tender_count asc,t1.last_tender_time asc,u.add_time asc";

        $query = $this->db->query($auto_sql);
        $borrow_auto_list = $query->result_array();

        foreach ($borrow_auto_list as $borrow_auto) {
            $borrow_result = self::get_borrow_obj($borrow_id); //获取借款标的单独信息
            if ($borrow_result['user_id'] == $borrow_auto['user_id']) {
                continue; //不能投自己的标
            }
            $tender_account = 0;
            $tender_account1 = 0;
            if ($borrow_auto['tender_type'] == 1) {
                $tender_account = $borrow_auto['tender_account'];
                $tender_account1 = $borrow_auto['tender_account1'];
            } elseif ($borrow_auto['tender_type'] == 2) {
                $tender_account = $borrow_auto['tender_scale'] * $borrow_result['account'] / 100;
                $tender_account1 = 100;
            }
            if ($tender_account < $borrow_result['lowest_account']) {
                continue; //不符合最低投资金额
            }
            if ($borrow_auto['borrow_style_status'] == 1) {
                if ($borrow_auto['borrow_style'] != $borrow_result['style']) {
                    continue; //不符合还款方式要求
                }
            }
            if ($borrow_auto['award_status'] == 1) {
                if ($borrow_auto['award_first'] > $borrow_result['funds'] ||
                        $borrow_auto['award_last'] < $borrow_result['funds']) {
                    continue; //不符合奖励要求
                }
            }
            if ($borrow_auto['apr_status'] == 1) {
                if ($borrow_auto['apr_first'] > $borrow_result['apr'] ||
                        $borrow_auto['apr_last'] < $borrow_result['apr']) {
                    continue; //不符合利率要求
                }
            }
            if ($borrow_auto['timelimit_status'] == 1) {
                if ($borrow_auto['timelimit_month_first'] > $borrow_result['time_limit'] ||
                        $borrow_auto['timelimit_month_last'] < $borrow_result['time_limit']) {
                    continue; //不符合期限要求
                }
            }
            if (($borrow_result['most_account'] != 0) && ($tender_account > $borrow_result['most_account'])) {
                continue;
            }
            /* if (($borrow_result['account'] < ($borrow_result['account_yes']+$tender_account))){
              continue;
              } */
            if (($borrow_result['account'] - $borrow_result['account_yes']) < $tender_account) {
                $tender_account = $borrow_result['account'] - $borrow_result['account_yes'];
            }
            $mode = $borrow_auto['user_id'] % 100;
            $this->load->model('Account_model');
            $user_account = $this->Account_model->get_account($borrow_auto['user_id']);

            $expMoney = $user_account['exp_money_12'] + $user_account['exp_money_24'];
            $user_account['use_money'] = $user_account['use_money'] - $expMoney;

            if ($user_account['use_money'] < $tender_account) {
                $tender_account = $user_account['use_money'];
            }
            if ($tender_account < $tender_account1) {
                continue;
            }
            if ($user_account['use_money'] < $tender_account) {
                continue;
            }
            if ($tender_account < $borrow_result['lowest_account']) {
                continue;
            }
            $data['id'] = $borrow_id;
            $data['ip'] = '127.0.0.1';
            $data['user_id'] = $borrow_auto['user_id'];
            $data['borrow_user_id'] = $borrow_result['user_id'];
            $data['money'] = $tender_account;
            $data['account'] = $tender_account;

            $auto_data['tender_count'] = intval($borrow_auto['tender_count'] + 1);
            $auto_data['last_tender_time'] = time();

            if ($borrow_result['ftype'] == 4) {
                $tender_acc = floor($tender_account / $borrow_result['lowest_account']);
                if ($tender_acc < 1) {
                    continue;
                }
                $data['account'] = $tender_acc * $borrow_result['lowest_account'];
                if ($user_account['use_money'] < $data['account']) {
                    continue;
                }
                //注册体验金自动投标
                if ($data['account'] >= 300 && $borrow_result['time_limit'] >= 12 && $user_account['reg_money'] == 100) {
                    if ($borrow_result['account'] - $borrow_result['account_yes'] - $data['account'] >= 100) {
                        $data['money'] = $data['money'] + 100;
                        $data['account'] = $data['account'] + 100;
                        self::reg_money_use(array('user_id' => $data['user_id']));
                    }
                }
                $this->update_borrow_auto($borrow_auto['id'], $auto_data);
                self::borrow_lz_tender($data);
            } else {
                $this->update_borrow_auto($borrow_auto['id'], $auto_data);
                self::borrow_tender($data);
            }
        }
    }

    /*
     * @param int $type 0月排行 2昨日排行 3日排行 4周排行 5总排行
     * */
    function index_total($type = 0) {
        $mkey = "index_total_" . $type;
        $this->mycache->delete($mkey);
        $ret = $this->mycache->get_array($mkey);
        if ($ret != false) {
            return $ret;
        }
        if ($type == 0) {//月排行
            $date = date("Y-m-d");
            $firstday = date("Y-m-01", strtotime($date));
            $lastday = date("Y-m-d", strtotime("$firstday +1 month"));
            $start = strtotime($firstday);
            $end = strtotime($lastday) - 1;
        } elseif ($type == 2) {//昨日排行
            $today = date('Y-m-d');
            $start = strtotime($today) - (3600 * 24);
            $end = strtotime($today);
        } else if ($type == 3) {//日排行
            $today = date('Y-m-d');
            $start = strtotime($today);
            $end = time();
        } elseif ($type == 4) {//周排行
            $date = date("Y-m-d");
            $firstday = strtotime("-1 Mon", strtotime($date));
            $lastday = date("Y-m-d", strtotime("+1 week",$firstday));
            $start = $firstday;
            $end = strtotime($lastday) - 1;
        }

        $limit = 5;
        $select = 'sum(t1.money) as money,t2.username,t2.sex,t2.realname';
        if ($type == 5) {
            $sql = "select {$select}
                    from zjy_user t2
                    left join zjy_borrow_tender t1 on t1.user_id=t2.user_id
                    left join zjy_borrow t3 on t1.borrow_id=t3.id
				    where t3.ftype!=5
                    GROUP BY t1.user_id
                    ORDER BY money DESC,t1.add_time ASC LIMIT {$limit}";
        } else if ($type == 2) {
            $sql = "select {$select}
                    from zjy_borrow_tender t1
                    left join zjy_user t2 on t1.user_id=t2.user_id
				    left join zjy_borrow t3 on t1.borrow_id=t3.id
				    where t1.add_time>$start and t1.add_time<$end AND t3.ftype!=5 and t3.is_day=0
				    GROUP BY t1.user_id having(sum(t1.account)>=50000)
				    ORDER BY money DESC,t1.add_time ASC LIMIT {$limit} ";
        } else {
            $sql = "select {$select}
                    from zjy_user t2
                    left join zjy_borrow_tender t1 on t1.user_id=t2.user_id
				    left join zjy_borrow t3 on t1.borrow_id=t3.id
				    where t1.add_time>$start and t1.add_time<$end AND t3.ftype!=5
                    GROUP BY t1.user_id ORDER BY money DESC,t1.add_time ASC LIMIT {$limit}";
        }

        $query = $this->db->query($sql);
        $ret = $query->result_array();
        $this->mycache->set_array($mkey, $ret, 180);
        return $ret;
    }

    function index_popularize($type = 0) {
        $mkey = "index_popularize_" . $type;
        $this->mycache->delete($mkey);
        $ret = $this->mycache->get_array($mkey);
        if ($ret != false) {
            return $ret;
        }

        if ($type == 0) {//月推广
            $date = date("Y-m-d");
            $firstday = date("Y-m-01", strtotime($date));
            $lastday = date("Y-m-d", strtotime("$firstday +1 month"));
            $start = strtotime($firstday);
            $end = strtotime($lastday) - 1;
        }

        if ($type == 1) { //累计推广人数
            $sql = "select count(user_id) as usernum,invite_userid,sum(invite_money) as money from zjy_user  where invite_userid > 0 and add_time GROUP BY invite_userid ORDER BY money DESC LIMIT 5;";
        } else {
            $sql = "select count(user_id) as usernum,invite_userid from zjy_user  where invite_userid > 0
					AND add_time>$start and add_time<$end
					GROUP BY invite_userid  ORDER BY usernum desc LIMIT 5";
        }

        $query = $this->db->query($sql);
        $result = $query->result_array();
        $ret = array();
        $this->load->model('User_model');
        foreach ($result as $v) {
            $userinfo = $this->User_model->get_one(array('user_id' => $v['invite_userid']));
            $v['username'] = $userinfo['username'];
            $ret[] = $v;
        }

        $this->mycache->set_array($mkey, $ret, 180);
        return $ret;
    }

    function get_user_collection($data = array()) {
        //封装查询内容
        $select = "*";
        if ($data['select'] == 1) {
            $select = " t1.id, t1.fstatus, t1.forder, t1.borrow_id, t1.repay_time,t1.repay_yestime,
						t1.repay_account, t1.interest, t1.capital, t1.late_days, t1.late_interest, t1.tender_id,
						t1.late_interest, t1.add_time, t2.id as borrow_id,
						t2.title, t2.account, t2.apr, t2.ftype, t2.time_limit, t2.is_day, t2.time_limit_day ";
        }

        //封装条件
        if (isset($data['where']['fstatus']) && $data['where']['fstatus'] == 0) {
            $_where = " where t2.fstatus=3 and t3.transfer_status<2 ";
        } else {
            $_where = " where t2.fstatus=3 ";
        }
        //$_where = " where t2.fstatus=3 and t3.transfer_status<2 ";
        if (isset($data['where']['user_id']) && $data['where']['user_id'] != '') {
            $_where .= " and t1.user_id = " . $data['where']['user_id'];
        }
        if (isset($data['where']['fstatus'])) {
            $_where .= " and t1.fstatus = " . $data['where']['fstatus'];
        }
        if (isset($data['where']['strtime']) && $data['where']['strtime'] != '') {
            $strtime = strtotime($data['where']['strtime']);
            $_where .= " and t1.repay_time >= " . $strtime;
        }
        if (isset($data['where']['endtime']) && $data['where']['endtime'] != '') {
            $endtime = strtotime($data['where']['endtime']) + 3600 * 24;
            $_where .= " and t1.repay_time < " . $endtime;
        }

        //排序
        $order = " order by t1.id asc ";
        if (isset($data['order']) && $data['order'] == 1) {
            $order = " order by t1.repay_time asc ";
        } elseif (isset($data['order']) && $data['order'] == 2) {
            $order = " order by t2.id asc ";
        } elseif (isset($data['order']) && $data['order'] == 3) {
            $order = " order by t1.id desc ";
        } elseif (isset($data['order']) && $data['order'] == 4) {
            $order = " order by t1.repay_yestime desc ";
        }

        //封装sql
        $page_size = $data['page_size'];
        $page_start = $data['page_start'];
        $sql_result = "select $select from zjy_borrow_collection as t1 left join zjy_borrow as t2 on t1.borrow_id=t2.id left join zjy_borrow_tender as t3 on t1.tender_id=t3.id ";
        $sql_result .= $_where;
        $sql_result .= $order;
        if (isset($data['limit']) && $data['limit'] == 'all') {
            $query = $this->db->query($sql_result);
            return $query->result_array();
        } else {
            $sql_result .= " limit $page_start, $page_size";
            $query = $this->db->query($sql_result);
            if (isset($data['list']) && $data['list'] == 1) {
                return $query->result_array();
            }
            $data['collection_list'] = $query->result_array();

            //总记录条数
            $sql_count = "select count(*) as count from zjy_borrow_collection as t1 left join zjy_borrow as t2 on t1.borrow_id=t2.id left join zjy_borrow_tender as t3 on t1.tender_id=t3.id ";
            $sql_count .= $_where;
            $query = $this->db->query($sql_count);
            $data['collection_count'] = $query->row()->count;
            return $data;
        }
        /*
          $query = $this->db->query($sql_result);
          if(isset($data['list']) && $data['list'] == 1){
          return $query->result_array();
          }
          $data['collection_list'] = $query->result_array();

          //总记录条数
          $sql_count = "select count(*) as count from zjy_borrow_collection as t1 left join zjy_borrow as t2 on t1.borrow_id=t2.id ";
          $sql_count .= $_where;
          $query = $this->db->query($sql_count);
          $data['collection_count'] = $query->row()->count;
          return $data;
         */
    }

    function get_user_borrow($data) {
        //封装查询内容
        $select = "*";
        if ($data['select'] == 1) {
            $select = " t1.id, t1.user_id, t1.title, t1.account , t1.apr, t1.funds, t1.time_limit , t1.style,
						t1.fstatus, t1.ftype, t1.award, t1.is_day, t1.time_limit_day, t1.verify_time, t1.account_yes,
						t1.valid_time, t1.end_time, t1.repayment_time, t1.repayment_account,t1.repayment_yesaccount, t1.add_time ";
        }

        //封装条件
        $_where = " where 1=1 ";
        if (isset($data['where']['user_id']) && $data['where']['user_id'] > 0) {
            $_where .= " and t1.user_id = " . $data['where']['user_id'];
        }
        if ($data['where']['fstatus'] === 0) {
            $_where .= " and t1.fstatus = " . $data['where']['fstatus'];
        } elseif (isset($data['where']['fstatus']) && $data['where']['fstatus'] != '') {
            $_where .= " and t1.fstatus = " . $data['where']['fstatus'];
        } else {
            $_where .= " and (t1.fstatus = 1 or t1.fstatus = 3)";
        }
        if (isset($data['where']['fstatus1']) && $data['where']['fstatus1'] == 'over') {
            $_where .= " and t1.repayment_account<=t1.repayment_yesaccount ";
        } elseif (isset($data['where']['fstatus1']) && $data['where']['fstatus1'] != '') {
            $_where .= " and t1.repayment_account = t1.repayment_yesaccount ";
        }

        //排序
        $_order = " order by t1.id desc ";

        //封装sql
        $page_size = $data['page_size'];
        $page_start = $data['page_start'];
        $sql_result = "select $select from zjy_borrow as t1 ";
        $sql_result .= $_where;
        $sql_result .= $_order;
        $sql_result .= " limit $page_start, $page_size";
        $query = $this->db->query($sql_result);
        $data['borrow_list'] = $query->result_array();

        //总记录条数
        $sql_count = "select count(*) as count from zjy_borrow as t1 ";
        $sql_count .= $_where;
        $query = $this->db->query($sql_count);
        $data['borrow_count'] = $query->row()->count;
        return $data;
    }

    /**
     * 撤标
     * @param $data
     */
    function Cancel($data = array()) {
        $borrow_id = $data['id'];
        $user_id = $data['user_id'];
        $ip = $data['ip'];
        $this->db->select("id,title,fstatus,apr,account,ftype");
        $this->db->where(array('id' => $borrow_id, 'user_id' => $user_id));
        $query = $this->db->get('zjy_borrow');
        $borrow_obj_result = $query->row_array();
        $this->load->model('Account_model');
        $status1 = $borrow_obj_result['fstatus'];
        if (($status1 == 0) || ($status1 == 1)) {
            $this->db->trans_start();
            $this->db->query("update zjy_borrow set fstatus=5 where id=$borrow_id and user_id=$user_id");
            $mode = $user_id % 100;
            if ($borrow_obj_result['ftype'] == 5) {//秒标解冻
                $user_account = $this->Account_model->get_account($user_id);
                $log['user_id'] = $user_account['user_id'];
                $log['ftype'] = BORROW_FROST; //解冻
                $log['money'] = $borrow_obj_result['account'] * $borrow_obj_result['apr'] / (100 * 12);
                $log['total'] = $user_account['total'];
                $log['use_money'] = $user_account['use_money'] + $log['money'];
                $log['no_use_money'] = $user_account['no_use_money'] - $log['money'];
                $log['collection'] = $user_account['collection'];
                $log['to_user'] = 1;
                $log['remark'] = "对[<a href='/borrow/obj/{$borrow_id}.html' target=_blank>{$borrow_obj_result['title']}</a>]借款的解冻";
                $log['add_time'] = time();
                $log['addip'] = $ip;
                $this->db->insert('zjy_account_log_' . $mode, $log);
                $this->db->query("update zjy_account set use_money=use_money+{$log['money']},no_use_money=no_use_money-{$log['money']} where user_id={$user_id};");
            }

            //返回所有投资者的金钱。

            $query = $this->db->query("select id,account,borrow_id,user_id,exp_money from zjy_borrow_tender where borrow_id={$borrow_id}");
            $tender_list = $query->result_array();
            foreach ($tender_list as $tender) {
                $mode = $tender['user_id'] % 100;
                unset($user_account);
                unset($log);
                $user_account = $this->Account_model->get_account($tender['user_id']);
                $log['user_id'] = $user_account['user_id'];
                $log['ftype'] = INVEST_FALSE; //扣除冻结款
                $log['money'] = $tender['account'];
                $log['total'] = $user_account['total'];
                $log['use_money'] = $user_account['use_money'] + $log['money'];
                $log['no_use_money'] = $user_account['no_use_money'] - $log['money'];
                $log['collection'] = $user_account['collection'];
                $log['to_user'] = $user_id;
                $log['remark'] = "招标[<a href='/borrow/obj/{$borrow_id}.html' target=_blank>{$borrow_obj_result['title']}</a>]失败返回的投标额";
                $log['add_time'] = time();
                $log['addip'] = $ip;

                $this->db->insert('zjy_account_log_' . $mode, $log);
                $this->db->query("update zjy_account set use_money=use_money+{$log['money']},no_use_money=no_use_money-{$log['money']},reg_money=reg_money+{$tender['exp_money']} where user_id={$tender['user_id']}");
                $this->db->query("update zjy_borrow_collection set fstatus=2 where tender_id={$tender['id']}");
                $this->db->query("update zjy_borrow_tender set fstatus=2 where id={$tender['id']}");
            }
            $this->db->trans_complete();
            if ($this->db->trans_status() == 1) {
                return 1;
            }
            return 0;
        } else {
            return 0;
        }
    }

    /**
     * 还款
     * @param $data
     */
    function repay($data = array()) {
        $repayment_id = $data['repayment_id'];
        $ip = $data['ip'];
		$userid = $data['user_id'];
        $this->load->model('Account_model');
        $this->load->model('User_model');
        $this->load->model('Message_model');
        $this->load->model('Credit_model');

        $sql = "select  p1.id,p1.borrow_id,p1.forder,p1.fstatus,p1.user_id,p1.repayment_time,
						p1.repayment_account,p1.interest,p1.capital,
						p2.title,p2.apr,p2.ftype,p2.style,
						p2.time_limit,p2.forst_account,p2.account,
						p2.success_time from zjy_borrow_repayment as p1 left join
						zjy_borrow as p2 on p1.borrow_id=p2.id where (p1.fstatus=0 or p1.fstatus=2)
						and p1.id=$repayment_id";
        $query = $this->db->query($sql);
        $repayment_obj_result = $query->row_array();
        $user_id = $repayment_obj_result['user_id'];
        $this->load->model('Account_model');
        if ($repayment_obj_result == false) {
            return "操作有误";
        }
        if ($repayment_obj_result['fstatus'] == 1) {
            return "此标已经还款，请不要乱操作";
        }

        if ($repayment_obj_result['forder'] != 0) {//判断上一期是否已还
            $_order = $repayment_obj_result['forder'] - 1;
            $sql_repay = "select fstatus from zjy_borrow_repayment where forder={$_order} and borrow_id={$repayment_obj_result['borrow_id']}";
            $query = $this->db->query($sql_repay);
            $result_repay = $query->row_array();
            if ($result_repay != false && $result_repay['fstatus'] != 1) {
                return "你上期的借款还没还，请先还上期的";
            }
        }
        $this->db->trans_start();
        $mode = $user_id % 100;
        if ($repayment_obj_result["ftype"] == 5) {
            $user_account = $this->Account_model->get_account($user_id);
            $log['user_id'] = $user_account['user_id'];
            $log['ftype'] = BORROW_FROST; //解冻
            $log['money'] = $repayment_obj_result['account'] * $repayment_obj_result['apr'] / (100 * 12);
            $log['total'] = $user_account['total'];
            $log['use_money'] = $user_account['use_money'] + $log['money'];
            $log['no_use_money'] = $user_account['no_use_money'] - $log['money'];
            $log['collection'] = $user_account['collection'];
            $log['to_user'] = 1;
            $log['remark'] = "对[<a href='/borrow/obj/{$repayment_obj_result['borrow_id']}.html' target=_blank>{$repayment_obj_result['title']}</a>]借款的解冻";
            $log['add_time'] = time();
            $log['addip'] = $ip;
            $this->db->insert('zjy_account_log_' . $mode, $log);
            $this->db->query("update zjy_account set use_money=use_money+{$log['money']},no_use_money=no_use_money-{$log['money']} where user_id={$user_id};");
        }

        //判断可用余额是否够还款
        if ($repayment_obj_result['capital'] > 0) {
            $late_result = late_interest($repayment_obj_result['repayment_time'], $repayment_obj_result['capital']);
        } else {
            $late_result = late_interest($repayment_obj_result['repayment_time'], $repayment_obj_result['interest']);
        }

        $user_account = $this->Account_model->get_account($user_id);
        if ($user_account['use_money'] < $repayment_obj_result['repayment_account'] + $late_result['late_interest']) {
            return "余额不足";
        }
        unset($log);
        $log['user_id'] = $user_account['user_id'];
        $log['ftype'] = REPAYMENT; //
        $log['money'] = $repayment_obj_result['repayment_account'];
        $log['total'] = $user_account['total'] - $log['money'];
        $log['use_money'] = $user_account['use_money'] - $log['money'];
        $log['no_use_money'] = $user_account['no_use_money'];
        $log['collection'] = $user_account['collection'];
        $log['to_user'] = 1;
        $log['op'] = 1;
        $log['remark'] = "对[<a href='/borrow/obj/{$repayment_obj_result['borrow_id']}.html' target=_blank>{$repayment_obj_result['title']}</a>]还款";
        $log['add_time'] = time();
        $log['addip'] = $ip;
        $this->db->insert('zjy_account_log_' . $mode, $log);
        $this->db->query("update zjy_account set total=total-{$log['money']},use_money=use_money-{$log['money']} where user_id={$user_id};");
        $re_time = (strtotime(date("Y-m-d", $repayment_obj_result['repayment_time'])) - strtotime(date("Y-m-d", time()))) / (60 * 60 * 24);

        /* if($repayment_obj_result['ftype'] != 3){
          //判断是否是最后的还款，是则解冻借款担保金
          if ($repayment_obj_result['forder']+1 == $repayment_obj_result['time_limit']){
          if($repayment_obj_result['ftype'] !=5){
          unset($user_account);
          unset($log);
          $user_account = $this->Account_model->get_account($user_id);
          $log['user_id'] 		= $user_account['user_id'];
          $log['ftype'] 			= BORROW_FROST;//解冻
          $log['money'] 			= $repayment_obj_result['forst_account'];
          $log['total'] 			= $user_account['total'];
          $log['use_money'] 		= $user_account['use_money']+$log['money'];
          $log['no_use_money'] 	= $user_account['no_use_money']-$log['money'];
          $log['collection'] 		= $user_account['collection'];
          $log['to_user'] 		= 1;
          $log['remark'] 			= "对[<a href='/borrow/obj/{$repayment_obj_result['borrow_id']}.html' target=_blank>{$repayment_obj_result['title']}</a>]借款的解冻";
          $log['add_time'] 		= time();
          $log['addip'] 			= $ip;
          $this->db->insert('zjy_account_log_'.$mode, $log);
          $this->db->query("update zjy_account set use_money=use_money+{$log['money']},no_use_money=no_use_money-{$log['money']} where user_id={$user_id};");
          }
          }
          } */

        $borrow = self::get_borrow_obj($repayment_id, $data = array());//$repayment_id其实是$borrow['id']
        $query = $this->db->query("select p1.id, p1.user_id,p1.repay_account,p1.interest,p1.tender_id,p1.capital,p2.transfer_status from zjy_borrow_collection as p1 left join  zjy_borrow_tender as p2 on p1.tender_id = p2.id where p1.forder={$repayment_obj_result['forder']} and p2.borrow_id={$repayment_obj_result['borrow_id']}");
        $collection_list = $query->result_array();
        foreach ($collection_list as $coll) {
            $mode = $coll['user_id'] % 100;
            //更新投资人的分期信息
            $this->db->query("update zjy_borrow_collection set repay_yestime='" . time() . "',repay_yesaccount = repay_account ,fstatus=1 where id={$coll['id']}");
            //更新投资的信息
            $this->db->query("update zjy_borrow_tender set repayment_yesaccount=repayment_yesaccount+{$coll['repay_account']},wait_account=wait_account-{$coll['repay_account']},wait_interest=wait_interest-{$coll['interest']},repayment_yesinterest=repayment_yesinterest+{$coll['interest']} where id={$coll['tender_id']}");

            //判断债权是否转让
            if ($coll['transfer_status'] == 3) {//已转让
                //购买债权人列表
                $this->load->model('Creditor_model');
                $buyers = $this->Creditor_model->get_buyers_by_tenderid($coll['tender_id']);
                $old_repay_account = $coll['repay_account']; //原回款金额
                foreach ($buyers as $buyer) {

                    //回款金额按比例分给债权购买人
                    $new_repay_account = intval($old_repay_account * $buyer['discount_buy'] / $buyer['discount_account'] * 100) / 100;
                    $umode = $buyer['user_id'] % 100;
                    $user_account = $this->Account_model->get_account($buyer['user_id']);
                    $log['user_id'] = $buyer['user_id'];
                    $log['ftype'] = INVEST_REPAYMENT;
                    $log['money'] = $new_repay_account;
                    $log['total'] = $user_account['total'];
                    $log['use_money'] = $user_account['use_money'] + $log['money'];
                    $log['no_use_money'] = $user_account['no_use_money'];
                    $log['collection'] = $user_account['collection'] - $log['money'];
                    $log['to_user'] = $user_id;
                    $log['remark'] = "客户对[<a href='/borrow/obj/{$repayment_obj_result['borrow_id']}.html' target=_blank>{$repayment_obj_result['title']}</a>]借款的还款";
                    $log['add_time'] = time();
                    $log['addip'] = $ip;
                    $this->db->insert('zjy_account_log_' . $umode, $log);
                    $this->db->query("update zjy_account set use_money=use_money+{$log['money']},collection=collection-{$log['money']} where user_id={$buyer['user_id']}");

                    //发送回款成功站内信
                    $this->Message_model->send(array('sent_user' => 1, 'receive_user' => $buyer['user_id'],
                        'name' => "恭喜您投资的‘{$borrow['title']}’已经成功回款{$log['money']}",
                        'fstatus' => 0,
                        'message_type' => 'system',
                        'sented' => 0,
                        'deltype' => 0,
                        'content' => "恭喜您投资的‘{$borrow['title']}’已经成功回款{$log['money']}",
                        'add_time' => time(),
                        'addip' => $this->js->get_ip()
                    ));

//                    MY_Controller::Notice(6,$buyer['user_id'],array('borrow_title'=>$borrow['title'],'use_money'=>$log['use_money']));

                    if ($buyer['repay_yesaccount'] + $new_repay_account >= $buyer['repay_account']) {
                        //已还完，多修改一个状态
                        $this->db->query("update zjy_creditor_log set repay_yesaccount=repay_yesaccount+{$new_repay_account},fstatus=3 where id={$buyer['id']}");
                    } else {
                        $this->db->query("update zjy_creditor_log set repay_yesaccount=repay_yesaccount+{$new_repay_account} where id={$buyer['id']}");
                    }
                    unset($log);
                }
            } else {//未转让
                unset($user_account);
                unset($log);
                $user_account = $this->Account_model->get_account($coll['user_id']);
                $log['user_id'] = $user_account['user_id'];
                $log['ftype'] = INVEST_REPAYMENT;
                $log['money'] = $coll['repay_account'];
                $log['total'] = $user_account['total'];
                $tobj = $this->Borrow_model->get_borrow_tender_obj($coll['tender_id']);
                if($tobj['is_exp'] == 1 && $tobj['exp_money'] != 0){
                    if($coll['capital'] > $tobj['exp_money']){
                        $log['money'] = $coll['repay_account']-$tobj['exp_money'];
                        $log['total'] = $user_account['total']-$tobj['exp_money'];
                        $this->db->query("update zjy_borrow_tender set exp_money=0 where id = {$coll['tender_id']}");//体验金扣完
                    }
                    if($coll['capital'] <= $tobj['exp_money']){
                        $use_exp_money = $tobj['exp_money']-$coll['capital'];//剩余体验金
                        $this->db->query("update zjy_borrow_tender set exp_money={$use_exp_money} where id = {$coll['tender_id']}");
                        $log['money'] = $coll['repay_account']-$coll['capital'];
                        $log['total'] = $user_account['total']-$coll['capital'];
                    }

                }
//            	if($coll['repay_account'] > $user_account['exp_money'] && $tobj['is_exp'] == 1 && $tobj['is_exp_repay'] == 0){
//            		$this->db->query("update zjy_borrow_tender set is_exp_repay=1 where id = {$coll['tender_id']}");
//                    $log['money'] = $coll['repay_account']-$user_account['exp_money'];
//                    $log['total'] = $user_account['total']-$user_account['exp_money'];
//                }
                $log['use_money'] = $user_account['use_money'] + $log['money'];
                $log['no_use_money'] = $user_account['no_use_money'];
                $log['collection'] = $user_account['collection'] - $coll['repay_account'];
                $log['to_user'] = $user_id;
                $log['remark'] = "客户对[<a href='/borrow/obj/{$repayment_obj_result['borrow_id']}.html' target=_blank>{$repayment_obj_result['title']}</a>]借款的还款";
                $log['add_time'] = time();
                $log['addip'] = $ip;
                $this->db->insert('zjy_account_log_' . $mode, $log);
                $this->db->query("update zjy_account set total={$log['total']},use_money=use_money+{$log['money']},collection=collection-{$coll['repay_account']} where user_id={$coll['user_id']};");

                //发送回款成功站内信
                $this->Message_model->send(array('sent_user' => 1, 'receive_user' => $coll['user_id'],
                    'name' => "恭喜您投资的‘{$borrow['title']}’已经成功回款{$log['money']}",
                    'fstatus' => 0,
                    'message_type' => 'system',
                    'sented' => 0,
                    'deltype' => 0,
                    'content' => "恭喜您投资的‘{$borrow['title']}’已经成功回款{$log['money']}",
                    'add_time' => time(),
                    'addip' => $this->js->get_ip()
                ));

//                MY_Controller::Notice(6,$coll['user_id'],array('borrow_title'=>$borrow['title'],'use_money'=>$log['use_money']));
                //扣除投资的管理费
                if (CON_INTEGRAL_FEE != 0) {
                    unset($user_account);
                    unset($log);
                    $user_account = $this->Account_model->get_account($coll['user_id']);
                    $log['user_id'] = $user_account['user_id'];
                    $log['ftype'] = TENDER_MANGE;
                    $log['money'] = $coll['interest'] * CON_INTEGRAL_FEE;
                    $log['total'] = $user_account['total'] - $log['money'];
                    $log['use_money'] = $user_account['use_money'] - $log['money'];
                    $log['no_use_money'] = $user_account['no_use_money'];
                    $log['collection'] = $user_account['collection'];
                    $log['to_user'] = 1;
                    $log['op'] = 1;
                    $log['remark'] = "用户成功还款扣除利息的管理费";
                    $log['add_time'] = time();
                    $log['addip'] = $ip;
                    $this->db->insert('zjy_account_log_' . $mode, $log);
                    $this->db->query("update zjy_account set total=total-{$log['money']},use_money=use_money-{$log['money']} where user_id={$coll['user_id']};");
                }
            }
        }
        if ($late_result['late_days'] > 0) {
            unset($user_account);
            unset($log);
            $user_account = $this->Account_model->get_account($user_id);
            $mode = $user_account['user_id'] % 100;
            $log['user_id'] = $user_account['user_id'];
            $log['ftype'] = LATE_REPAYMENT;
            $log['money'] = $late_result['late_interest'];
            $log['total'] = $user_account['total'] - $log['money'];
            $log['use_money'] = $user_account['use_money'] - $log['money'];
            $log['no_use_money'] = $user_account['no_use_money'];
            $log['collection'] = $user_account['collection'];
            $log['to_user'] = 1;
            $log['op'] = 1;
            $log['remark'] = "对[<a href='/borrow/obj/{$repayment_obj_result['borrow_id']}.html' target=_blank>{$repayment_obj_result['title']}</a>]借款的逾期金额的扣除";
            $log['add_time'] = time();
            $log['addip'] = $ip;
            $this->db->insert('zjy_account_log_' . $mode, $log);
            $this->db->query("update zjy_account set total=total-{$log['money']},use_money=use_money-{$log['money']} where user_id={$user_account['user_id']};");

            //更新逾期的信息
            $this->db->query("update zjy_borrow_repayment set late_days='{$late_result['late_days']}',late_interest = '{$late_result['late_interest']}' where id = {$repayment_id}");
            $_order = $repayment_obj_result['forder'];
            if ($late_result['late_days'] <= 30) {
                $sql = "select p1.id,p1.capital,p1.interest,p2.user_id from zjy_borrow_collection as p1 left join  zjy_borrow_tender as p2 on
								p1.tender_id=p2.id where p1.`forder`='{$_order}' and p2.borrow_id='{$repayment_obj_result['borrow_id']}'";
                $query = $this->db->query($sql);
                $coll_result = $query->result_array();
                $late_rate = CON_LATE_RATE;
                foreach ($coll_result as $value) {
                    //更新投资的信息
                    $mode = $value['user_id'] % 100;
                    unset($user_account);
                    unset($log);
                    $user_account = $this->Account_model->get_account($value['user_id']);
                    $log['user_id'] = $value['user_id'];
                    $log['ftype'] = LATE_COLLECTION;
                    if ($value['capital'] > 0) {
                        $log['money'] = round((($value['capital'] * CON_LATE_RATE * $late_result['late_days']) / 2), 2);
                    } else {
                        $log['money'] = round((($value['interest'] * CON_LATE_RATE * $late_result['late_days']) / 2), 2);
                    }
                    $log['total'] = $user_account['total'] + $log['money'];
                    $log['use_money'] = $user_account['use_money'] + $log['money'];
                    $log['no_use_money'] = $user_account['no_use_money'];
                    $log['collection'] = $user_account['collection'];
                    $log['to_user'] = $userid;
                    $log['remark'] = "[<a href='/borrow/obj/{$repayment_obj_result['borrow_id']}.html' target=_blank>{$repayment_obj_result['title']}</a>]借款标逾期并少于30天的逾期利息收入";
                    $log['add_time'] = time();
                    $log['addip'] = $ip;
                    $this->db->insert('zjy_account_log_' . $mode, $log);
                    $this->db->query("update zjy_account set total=total+{$log['money']},use_money=use_money+{$log['money']} where user_id={$value['user_id']};");

                    //更新逾期的信息
                    $this->db->query("update zjy_borrow_collection set late_days='{$late_result['late_days']}',late_interest='{$log['money']}' where id = {$value['id']}");
                }
            } else {
                $sql = "select p1.id,p1.capital,p1.interest,p2.user_id,p2.id as t_id from zjy_borrow_collection as p1 left join  zjy_borrow_tender as p2 on
				p1.tender_id=p2.id where p1.`forder`='{$_order}' and p2.borrow_id='{$repayment_obj_result['borrow_id']}'";
                $query = $this->db->query($sql);
                $coll_result = $query->result_array();
                foreach ($coll_result as $value) {
                    //更新投资的信息
                    $mode = $value['user_id'] % 100;
                    unset($user_account);
                    unset($log);
                    $user_account = $this->Account_model->get_account($value['user_id']);
                    $log['user_id'] = $value['user_id'];
                    $log['ftype'] = LATE_COLLECTION;
                    if ($value['capital'] > 0) {
                        $log['money'] = round((($value['capital'] * CON_LATE_RATE1 * $late_result['late_days']) / 2), 2);
                    } else {
                        $log['money'] = round((($value['interest'] * CON_LATE_RATE1 * $late_result['late_days']) / 2), 2);
                    }
                    $log['total'] = $user_account['total'] + $log['money'];
                    $log['use_money'] = $user_account['use_money'] + $log['money'];
                    $log['no_use_money'] = $user_account['no_use_money'];
                    $log['collection'] = $user_account['collection'];
                    $log['to_user'] = $data['user_id'];
                    $log['remark'] = "[<a href='/borrow/obj/{$repayment_obj_result['borrow_id']}.html' target=_blank>{$repayment_obj_result['title']}</a>]借款标逾期并少于30天的逾期利息收入";
                    $log['add_time'] = time();
                    $log['addip'] = $ip;
                    $this->db->insert('zjy_account_log_' . $mode, $log);
                    $this->db->query("update zjy_account set total=total+{$log['money']},use_money=use_money+{$log['money']} where user_id={$value['user_id']};");

                    //更新逾期的信息
                    $this->db->query("update zjy_borrow_collection set late_days='{$late_result['late_days']}',late_interest='{$log['money']}' where id = {$value['id']}");
                }
            }
        }
        //添加最后的还款金额
        $this->db->query("update zjy_borrow set repayment_yesaccount=repayment_yesaccount+{$repayment_obj_result['repayment_account']} where id={$repayment_obj_result['borrow_id']}");

        //更新还款标的状态
        $this->db->query("update zjy_borrow_repayment set fstatus=1,repayment_yesaccount={$repayment_obj_result['repayment_account']},repayment_yestime=" . time() . " where id=$repayment_id");

        //更新所借款的还款金额  2013-12-12 错误代码，需要检查之前的数据
        //$this->db->query("update zjy_borrow_tender set interest=interest+{$repayment_obj_result['interest']},repayment_yesaccount=repayment_yesaccount+{$repayment_obj_result['capital']} where id={$repayment_obj_result['borrow_id']}");
        $this->db->trans_complete();
        if ($this->db->trans_status() == 1) {
            return 1;
        }
        return "还款失败";
    }

    /**
     * 流转标还款
     * @param Array $data
     * @return Array
     */
    function lz_repay($data = array()) {
        $id = $data['collection_id'];
        $ip = $data['ip'];
        $this->load->model('Account_model');
        $this->load->model('User_model');
        $this->load->model('Message_model');
        $this->load->model('Credit_model');

        $yestoday = strtotime(date('Y-m-d'));
        $nextday = strtotime(date('Y-m-d 23:59:59'));

        $query = $this->db->query("SELECT count(*) as count FROM zjy_borrow_collection
									WHERE repay_time>=$yestoday AND repay_time<=$nextday AND
									fstatus=0 and id=$id ");
        $result_count = $query->row_array();
        /* if($result_count['count'] == 0){
          return "此借款还未到还款期，请不要乱操作";
          } */

        $query = $this->db->query(" select p1.user_id,p1.id,p1.fstatus,p1.forder,p1.tender_id,p1.repay_time,p1.repay_yestime,
									p1.repay_account,p1.repay_yesaccount,p1.interest,p1.capital,p1.late_days,
									p1.interest,p1.add_time,p2.borrow_id,p2.account,p3.user_id as borrow_userid,
									p3.time_limit,p3.title,p3.style
									from zjy_borrow_collection as p1 left join zjy_borrow_tender as p2
									on p1.tender_id=p2.id left join zjy_borrow as p3 on p2.borrow_id=p3.id
									where p1.id=$id");

        $borrow_repayment_result = $query->row_array();
        $borrow_id = $borrow_repayment_result["borrow_id"];
        $success_time = $borrow_repayment_result["add_time"];
        $borrow_userid = $borrow_repayment_result["borrow_userid"];

        if ($borrow_repayment_result['fstatus'] == 1) {
            return "此借款已经还款，请不要乱操作";
        }

        //判断上一期是否已还
        if ($borrow_repayment_result['forder'] != 0) {
            $_order = $borrow_repayment_result['forder'] - 1;
            $query_repay = $this->db->query("select fstatus from zjy_borrow_collection where forder=$_order and borrow_id={$borrow_id}");
            $result_repay = $query_repay->row_array();
            if ($result_repay != false && $result_repay['fstatus'] != 1) {
                return "你上期的借款还没还，请先还上期的";
            }
        }
        if ($borrow_repayment_result['capital'] > 0) {
            $late_result = late_interest($borrow_repayment_result['repay_time'], $borrow_repayment_result['capital']);
        } else {
            $late_result = late_interest($borrow_repayment_result['repay_time'], $borrow_repayment_result['interest']);
        }


        //判断可用余额是否够还款
        $user_account = $this->Account_model->get_account($borrow_userid);
        if ($user_account['use_money'] < $borrow_repayment_result['repay_account'] + $late_result['late_interest']) {
            return "账户余额不足，请充值。";
        }
        $this->db->trans_start();
        //扣除可用余额还款部分
        $bmode = $borrow_userid % 100;
        $user_account = $this->Account_model->get_account($borrow_userid);
        $log['user_id'] = $borrow_userid;
        $log['ftype'] = REPAYMENT;
        $log['money'] = $borrow_repayment_result['repay_account'];
        $log['total'] = $user_account['total'] - $log['money'];
        $log['use_money'] = $user_account['use_money'] - $log['money'];
        $log['no_use_money'] = $user_account['no_use_money'];
        $log['collection'] = $user_account['collection'];
        $log['to_user'] = "0";
        $log['remark'] = "对[<a href='/borrow/obj/{$borrow_repayment_result['borrow_id']}.html' target=_blank>{$borrow_repayment_result['title']}</a>]还款";
        $log['add_time'] = time();
        $log['addip'] = $ip;
        $this->db->insert('zjy_account_log_' . $bmode, $log);
        $this->db->query("update zjy_account set total=total-{$log['money']},use_money=use_money-{$log['money']} where user_id={$borrow_userid}");

        $_repay_time = $borrow_repayment_result['repay_time'];
        $re_time = (strtotime(date("Y-m-d", $_repay_time)) - strtotime(date("Y-m-d", time()))) / (60 * 60 * 24);

        $_repay_time = $borrow_repayment_result['repay_time'];
        $re_time = (strtotime(date("Y-m-d", $_repay_time)) - strtotime(date("Y-m-d", time()))) / (60 * 60 * 24);
        $credit_type = CREDIT_ADVANCE_DAY;
        if ($re_time > 4) {
            $credit_type = CREDIT_ADVANCE_3DAY;
        } elseif ($re_time > 2 && $re_time <= 4) {
            $credit_type = CREDIT_ADVANCE_1DAY;
        }
        //增加积分
        /*
          $this->Credit_model->incr_credit(array('user_id'=>$borrow_repayment_result['user_id'],
          'type_id'=>14,
          'op'=>1,
          'credit_value'=>5,
          'remark'=>'还款成功加5分',
          'op_user'=>$borrow_repayment_result['user_id'],
          'add_time'=>time(),
          'addip'=>$ip));
         */

        //判断是否是最后的还款，是则解冻借款担保金
        if ($borrow_repayment_result['capital'] > 0) {
            /* $user_account = $this->Account_model->get_account($borrow_userid);
              $log['user_id'] 		= $borrow_userid;
              $log['ftype'] 			= BORROW_FROST;
              $log['money'] 			= $borrow_repayment_result['capital']*0.1;
              $log['total'] 			= $user_account['total'];
              $log['use_money'] 		= $user_account['use_money']+$log['money'];
              $log['no_use_money'] 	= $user_account['no_use_money']-$log['money'];
              $log['collection'] 		= $user_account['collection'];
              $log['to_user'] 		= "1";
              $log['remark'] 			= "对[<a href='/borrow/obj/{$borrow_repayment_result['borrow_id']}.html' target=_blank>{$borrow_repayment_result['title']}</a>]借款的解冻";
              $log['add_time'] 	= time();
              $log['addip'] 		= $ip;
              $this->db->insert('zjy_account_log_'.$bmode, $log);
              $this->db->query("update zjy_account set use_money=use_money+{$log['money']},no_use_money=no_use_money-{$log['money']} where user_id={$borrow_userid}");
             */
            //增加积分
            $this->Credit_model->incr_credit(array('user_id' => $borrow_userid,
                'type_id' => 8,
                'op' => 1,
                'credit_value' => $borrow_repayment_result['capital'] / 100,
                'remark' => "借款成功加" . ($borrow_repayment_result['capital'] / 100) . "分",
                'op_user' => $borrow_repayment_result['user_id'],
                'add_time' => time(),
                'addip' => $ip));
        }

        $_order = $borrow_repayment_result['forder'];

        //如果网站已经待还，就不用还
        if ($borrow_repayment_result['fstatus'] != 2) {
            $query = $this->db->query("select p1.*,p2.user_id,p2.transfer_status from zjy_borrow_collection as p1 left join zjy_borrow_tender as p2 on p1.tender_id = p2.id where p1.forder='{$_order}' and p1.id='{$borrow_repayment_result['id']}'");
            $result = $query->result_array();
            foreach ($result as $key => $value) {
                //更新投资人的分期信息
                $this->db->query("update zjy_borrow_collection set repay_yestime='" . time() . "',repay_yesaccount = repay_account,fstatus=1 where id = '{$value['id']}'");

                //更新投资的信息
                $interest_tmp = round($value['interest'], 2);
                $this->db->query(" update zjy_borrow_tender set repayment_yesaccount=repayment_yesaccount+{$value['repay_account']},
									wait_account=wait_account-{$value['repay_account']},wait_interest=wait_interest-{$interest_tmp},
									repayment_yesinterest=repayment_yesinterest+{$value['interest']} where id='{$value['tender_id']}'");

                //判断债权是否转让
                if ($value['transfer_status'] == 3) {//已转让
                    //购买债权人列表
                    $this->load->model('Creditor_model');
                    $buyers = $this->Creditor_model->get_buyers_by_tenderid($value['tender_id']);
                    $old_repay_account = $value['repay_account']; //原回款金额
                    foreach ($buyers as $buyer) {
                        //回款金额按比例分给债权购买人
                        $new_repay_account = intval($old_repay_account * $buyer['discount_buy'] / $buyer['discount_account'] * 100) / 100;
                        $umode = $buyer['user_id'] % 100;
                        $user_account = $this->Account_model->get_account($buyer['user_id']);
                        $log['user_id'] = $buyer['user_id'];
                        $log['ftype'] = INVEST_REPAYMENT;
                        $log['money'] = $new_repay_account;
                        $log['total'] = $user_account['total'];
                        $log['use_money'] = $user_account['use_money'] + $log['money'];
                        $log['no_use_money'] = $user_account['no_use_money'];
                        $log['collection'] = $user_account['collection'] - $log['money'];
                        $log['to_user'] = $borrow_userid;
                        $log['remark'] = "客户对[<a href='/borrow/obj/{$borrow_repayment_result['borrow_id']}.html' target=_blank>{$borrow_repayment_result['title']}</a>]借款的还款";
                        $log['add_time'] = time();
                        $log['addip'] = $ip;
                        $this->db->insert('zjy_account_log_' . $umode, $log);
                        $this->db->query("update zjy_account set use_money=use_money+{$log['money']},collection=collection-{$log['money']} where user_id={$buyer['user_id']}");
                        if ($buyer['repay_yesaccount'] + $new_repay_account >= $buyer['repay_account']) {
                            //已还完，多修改一个状态
                            $this->db->query("update zjy_creditor_log set repay_yesaccount=repay_yesaccount+{$new_repay_account},fstatus=3 where id={$buyer['id']}");
                        } else {
                            $this->db->query("update zjy_creditor_log set repay_yesaccount=repay_yesaccount+{$new_repay_account} where id={$buyer['id']}");
                        }

                        unset($log);
                    }
                } else {//未转让
                    $umode = $value['user_id'] % 100;
                    $user_account = $this->Account_model->get_account($value['user_id']);
                    $log['user_id'] = $value['user_id'];
                    $log['ftype'] = INVEST_REPAYMENT;
                    $log['money'] = $value['repay_account'];
                    $log['total'] = $user_account['total'];
                    $log['use_money'] = $user_account['use_money'] + $log['money'];
                    $log['no_use_money'] = $user_account['no_use_money'];
                    $log['collection'] = $user_account['collection'] - $log['money'];
                    $log['to_user'] = $borrow_userid;
                    $log['remark'] = "客户对[<a href='/borrow/obj/{$borrow_repayment_result['borrow_id']}.html' target=_blank>{$borrow_repayment_result['title']}</a>]借款的还款";
                    $log['add_time'] = time();
                    $log['addip'] = $ip;
                    $this->db->insert('zjy_account_log_' . $umode, $log);
                    $this->db->query("update zjy_account set use_money=use_money+{$log['money']},collection=collection-{$log['money']} where user_id={$value['user_id']}");

                    //提醒设置
                    $this->Message_model->send(array('sent_user' => 1, 'receive_user' => $borrow_repayment_result['user_id'],
                        'name' => "客户对[<a href='/borrow/obj/{$borrow_repayment_result['borrow_id']}.html' target=_blank>{$borrow_repayment_result['title']}</a>]借款的还款",
                        'fstatus' => 0, 'message_type' => 'system', 'sented' => 0, 'deltype' => 0,
                        'content' => "客户在" . date("Y-m-d H:i:s") . "对[<a href='/borrow/obj/{$borrow_repayment_result['borrow_id']}.html' target=_blank>{$borrow_repayment_result['title']}</a>]借款的还款,还款金额为{$value['repay_account']}",
                        'add_time' => time(), 'addip' => $ip));
                }
            }
        }

        //逾期还款
        if ($late_result['late_days'] > 0) {
            $user_account = $this->Account_model->get_account($borrow_userid);
            $mode = $borrow_userid % 100;
            $log['user_id'] = $borrow_userid;
            $log['ftype'] = LATE_REPAYMENT;
            $log['money'] = $late_result['late_interest'];
            $log['total'] = $user_account['total'] - $log['money'];
            $log['use_money'] = $user_account['use_money'] - $log['money'];
            $log['no_use_money'] = $user_account['no_use_money'];
            $log['collection'] = $user_account['collection'];
            $log['to_user'] = 1;
            $log['remark'] = "对[<a href='/borrow/obj{$borrow_repayment_result['borrow_id']}.html target=_blank>{$borrow_repayment_result['title']}</a>]借款的逾期金额的扣除";
            $log['add_time'] = time();
            $log['addip'] = $ip;
            $this->db->insert('zjy_account_log_' . $mode, $log);
            $this->db->query("update zjy_account set total=total-{$log['money']},use_money=use_money-{$log['money']} where user_id={$borrow_userid}");

            //更新逾期的信息
            $this->db->query("update zjy_borrow_repayment set late_days='{$late_result['late_days']}',late_interest='{$late_result['late_interest']}' where id = {$id}");

            if ($late_result['late_days'] <= 30) {
                $this->db->query("select p1.*,p2.user_id from zjy_borrow_collection as p1 left join zjy_borrow_tender as p2 on
								  p1.tender_id=p2.id where p1.id=$id");
                $result = $query->row_array();
                $mode = $value['user_id'] % 100;
                //更新投资的信息
                $user_account = $this->Account_model->get_account($value['user_id']);
                $log['user_id'] = $value['user_id'];
                $log['ftype'] = LATE_COLLECTION;
                if ($value['capital'] > 0) {
                    $log['money'] = round((($value['capital'] * CON_LATE_RATE * $late_result['late_days']) / 2), 2);
                } else {
                    $log['money'] = round((($value['interest'] * CON_LATE_RATE * $late_result['late_days']) / 2), 2);
                }

                $log['total'] = $user_account['total'] + $log['money'];
                $log['use_money'] = $user_account['use_money'] + $log['money'];
                $log['no_use_money'] = $user_account['no_use_money'];
                $log['collection'] = $user_account['collection'];
                $log['to_user'] = $data['user_id'];
                $log['remark'] = "[<a href='/borrow/obj/{$borrow_repayment_result['borrow_id']}.html target=_blank>{$borrow_repayment_result['title']}</a>]借款标逾期并少于30天的逾期利息收入";
                $log['add_time'] = time();
                $log['addip'] = $ip;
                $this->db->insert('zjy_account_log_' . $mode, $log);
                $this->db->query("update zjy_account set total=total+{$log['money']},use_money=use_money+{$log['money']} where user_id={$value['user_id']}");

                //更新逾期的信息
                $this->db->query("update zjy_borrow_collection set late_days='{$late_result['late_days']}',late_interest='{$log['money']}' where id={$id}");
            } else {
                $this->db->query("select p1.*,p2.user_id from zjy_borrow_collection as p1 left join zjy_borrow_tender as p2 on
						p1.tender_id=p2.id where p1.id=$id");
                $result = $query->row_array();
                $mode = $value['user_id'] % 100;
                //更新投资的信息
                $user_account = $this->Account_model->get_account($value['user_id']);
                $log['user_id'] = $value['user_id'];
                $log['ftype'] = LATE_COLLECTION;
                if ($value['capital'] > 0) {
                    $log['money'] = round((($value['capital'] * CON_LATE_RATE1 * $late_result['late_days']) / 2), 2);
                } else {
                    $log['money'] = round((($value['interest'] * CON_LATE_RATE1 * $late_result['late_days']) / 2), 2);
                }
                $log['total'] = $user_account['total'] + $log['money'];
                $log['use_money'] = $user_account['use_money'] + $log['money'];
                $log['no_use_money'] = $user_account['no_use_money'];
                $log['collection'] = $user_account['collection'];
                $log['to_user'] = $data['user_id'];
                $log['remark'] = "[<a href='/borrow/obj/{$borrow_repayment_result['borrow_id']}.html target=_blank>{$borrow_repayment_result['title']}</a>]借款标逾期并少于30天的逾期利息收入";
                $log['add_time'] = time();
                $log['addip'] = $ip;
                $this->db->insert('zjy_account_log_' . $mode, $log);
                $this->db->query("update zjy_account set total=total+{$log['money']},use_money=use_money+{$log['money']} where user_id={$value['user_id']}");

                //更新逾期的信息
                $this->db->query("update zjy_borrow_collection set late_days='{$late_result['late_days']}',late_interest='{$log['money']}' where id={$id}");
            }
        }

        //添加最后的还款金额
        $this->db->query("update zjy_borrow set lz_endtime=verify_time+604800, account_yes=account_yes-{$borrow_repayment_result['capital']},repayment_yesaccount= repayment_yesaccount + {$borrow_repayment_result['repay_account']} where id={$borrow_repayment_result['borrow_id']}");
        //$this->db->query("select count(*) as count from zjy_borrow_collection where tender_id in (select id from {borrow_tender} where borrow_id={$borrow_repayment_result['borrow_id']}) and status=0");
        $this->db->trans_complete();
        if ($this->db->trans_status() == 1) {
            return 1;
        }
        return 1;
    }

    function get_tender_obj($id) {
        $query = $this->db->query("select * from zjy_borrow_tender where id=" . $id);
        return $query->row_array();
    }

    function sl_repay($data = array()) {
        $id = $data['collection_id'];
        $ip = $data['ip'];
        $this->load->model('Account_model');
        $this->load->model('User_model');
        $this->load->model('Message_model');
        $this->load->model('Credit_model');

        $yestoday = strtotime(date('Y-m-d'));
        $nextday = strtotime(date('Y-m-d 23:59:59'));

        $query = $this->db->query("SELECT count(*) as count FROM zjy_borrow_collection
									WHERE repay_time>=$yestoday AND repay_time<=$nextday AND
									fstatus=0 and id=$id ");
        $result_count = $query->row_array();
        /* if($result_count['count'] == 0){
          return "此借款还未到还款期，请不要乱操作";
          } */

        $query = $this->db->query(" select p1.user_id,p1.id,p1.fstatus,p1.forder,p1.tender_id,p1.repay_time,p1.repay_yestime,
									p1.repay_account,p1.repay_yesaccount,p1.interest,p1.capital,p1.late_days,
									p1.interest,p1.add_time,p2.borrow_id,p2.account,p3.user_id as borrow_userid,
									p3.time_limit_day,p3.title,p3.style
									from zjy_borrow_collection as p1 left join zjy_borrow_tender as p2
									on p1.tender_id=p2.id left join zjy_borrow as p3 on p2.borrow_id=p3.id
									where p1.id=$id");

        $borrow_repayment_result = $query->row_array();
        $borrow_id = $borrow_repayment_result["borrow_id"];
        $success_time = $borrow_repayment_result["add_time"];
        $borrow_userid = $borrow_repayment_result["borrow_userid"];

        if ($borrow_repayment_result['fstatus'] == 1) {
            return "此借款已经还款，请不要乱操作";
        }

        //判断上一期是否已还
        if ($borrow_repayment_result['forder'] != 0) {
            $_order = $borrow_repayment_result['forder'] - 1;
            $query_repay = $this->db->query("select fstatus from zjy_borrow_collection where forder=$_order and borrow_id={$borrow_id}");
            $result_repay = $query_repay->row_array();
            if ($result_repay != false && $result_repay['fstatus'] != 1) {
                return "你上期的借款还没还，请先还上期的";
            }
        }
        if ($borrow_repayment_result['capital'] > 0) {
            $late_result = late_interest($borrow_repayment_result['repay_time'], $borrow_repayment_result['capital']);
        } else {
            $late_result = late_interest($borrow_repayment_result['repay_time'], $borrow_repayment_result['interest']);
        }


        //判断可用余额是否够还款
        $user_account = $this->Account_model->get_account($borrow_userid);
        if ($user_account['use_money'] < $borrow_repayment_result['repay_account'] + $late_result['late_interest']) {
            return "账户余额不足，请充值。";
        }
        $this->db->trans_start();
        //扣除可用余额还款部分
        $bmode = $borrow_userid % 100;
        $user_account = $this->Account_model->get_account($borrow_userid);
        $log['user_id'] = $borrow_userid;
        $log['ftype'] = REPAYMENT;
        $log['money'] = $borrow_repayment_result['repay_account'];
        $log['total'] = $user_account['total'] - $log['money'];
        $log['use_money'] = $user_account['use_money'] - $log['money'];
        $log['no_use_money'] = $user_account['no_use_money'];
        $log['collection'] = $user_account['collection'];
        $log['to_user'] = "0";
        $log['remark'] = "对[<a href='/borrow/slobj/{$borrow_repayment_result['borrow_id']}.html' target=_blank>{$borrow_repayment_result['title']}</a>]还款";
        $log['add_time'] = time();
        $log['addip'] = $ip;
        $this->db->insert('zjy_account_log_' . $bmode, $log);
        $this->db->query("update zjy_account set total=total-{$log['money']},use_money=use_money-{$log['money']} where user_id={$borrow_userid}");

        //判断是否是最后的还款，是则解冻借款担保金
        if ($borrow_repayment_result['capital'] > 0) {
            /* $user_account = $this->Account_model->get_account($borrow_userid);
              $log['user_id'] 		= $borrow_userid;
              $log['ftype'] 			= BORROW_FROST;
              $log['money'] 			= $borrow_repayment_result['capital']*0.1;
              $log['total'] 			= $user_account['total'];
              $log['use_money'] 		= $user_account['use_money']+$log['money'];
              $log['no_use_money'] 	= $user_account['no_use_money']-$log['money'];
              $log['collection'] 		= $user_account['collection'];
              $log['to_user'] 		= "1";
              $log['remark'] 			= "对[<a href='/borrow/slobj/{$borrow_repayment_result['borrow_id']}.html' target=_blank>{$borrow_repayment_result['title']}</a>]借款的解冻";
              $log['add_time'] 	= time();
              $log['addip'] 		= $ip;
              $this->db->insert('zjy_account_log_'.$bmode, $log);
              $this->db->query("update zjy_account set use_money=use_money+{$log['money']},no_use_money=no_use_money-{$log['money']} where user_id={$borrow_userid}");
             */
            //增加积分
            $this->Credit_model->incr_credit(array('user_id' => $borrow_userid,
                'type_id' => 8,
                'op' => 1,
                'credit_value' => $borrow_repayment_result['capital'] / 100,
                'remark' => "借款成功加" . ($borrow_repayment_result['capital'] / 100) . "分",
                'op_user' => $borrow_repayment_result['user_id'],
                'add_time' => time(),
                'addip' => $ip));
        }

        $_order = $borrow_repayment_result['forder'];

        //如果网站已经待还，就不用还
        if ($borrow_repayment_result['fstatus'] != 2) {
            $query = $this->db->query("select p1.*,p2.user_id from zjy_borrow_collection as p1 left join zjy_borrow_tender as p2 on p1.tender_id = p2.id where p1.forder='{$_order}' and p1.id='{$borrow_repayment_result['id']}'");
            $result = $query->result_array();
            foreach ($result as $key => $value) {
                //更新投资人的分期信息
                $this->db->query("update zjy_borrow_collection set repay_yestime='" . time() . "',repay_yesaccount = repay_account,fstatus=1 where id = '{$value['id']}'");

                //更新投资的信息
                $interest_tmp = round($value['interest'], 2);
                $this->db->query(" update zjy_borrow_tender set repayment_yesaccount=repayment_yesaccount+{$value['repay_account']},
									wait_account=wait_account-{$value['repay_account']},wait_interest=wait_interest-{$interest_tmp},
									repayment_yesinterest=repayment_yesinterest+{$value['interest']} where id='{$value['tender_id']}'");
                $umode = $value['user_id'] % 100;
                $user_account = $this->Account_model->get_account($value['user_id']);
                $log['user_id'] = $value['user_id'];
                $log['ftype'] = INVEST_REPAYMENT;
                $log['money'] = $value['repay_account'];
                $log['total'] = $user_account['total'];
                $log['use_money'] = $user_account['use_money'] + $log['money'];
                $log['no_use_money'] = $user_account['no_use_money'];
                $log['collection'] = $user_account['collection'] - $log['money'];
                $log['to_user'] = $borrow_userid;
                $log['remark'] = "客户对[<a href='/borrow/slobj/{$borrow_repayment_result['borrow_id']}.html' target=_blank>{$borrow_repayment_result['title']}</a>]借款的还款";
                $log['add_time'] = time();
                $log['addip'] = $ip;
                $this->db->insert('zjy_account_log_' . $umode, $log);
                $this->db->query("update zjy_account set use_money=use_money+{$log['money']},collection=collection-{$log['money']} where user_id={$value['user_id']}");

                //提醒设置
                $this->Message_model->send(array('sent_user' => 1, 'receive_user' => $borrow_repayment_result['user_id'],
                    'name' => "客户对[<a href='/borrow/obj/{$borrow_repayment_result['borrow_id']}.html' target=_blank>{$borrow_repayment_result['title']}</a>]借款的还款",
                    'fstatus' => 0, 'message_type' => 'system', 'sented' => 0, 'deltype' => 0,
                    'content' => "客户在" . date("Y-m-d H:i:s") . "对[<a href='/borrow/slobj/{$borrow_repayment_result['borrow_id']}.html' target=_blank>{$borrow_repayment_result['title']}</a>]借款的还款,还款金额为{$value['repay_account']}",
                    'add_time' => time(), 'addip' => $ip));
            }
        }

        //添加最后的还款金额
        //$this->db->query("update zjy_borrow set lz_endtime=verify_time+604800, account_yes=account_yes-{$borrow_repayment_result['capital']},repayment_yesaccount= repayment_yesaccount + {$borrow_repayment_result['repay_account']} where id={$borrow_repayment_result['borrow_id']}");
        $this->db->query("update zjy_borrow set lz_endtime=verify_time+604800, repayment_yesaccount= repayment_yesaccount + {$borrow_repayment_result['repay_account']} where id={$borrow_repayment_result['borrow_id']}");

        //$this->db->query("select count(*) as count from zjy_borrow_collection where tender_id in (select id from {borrow_tender} where borrow_id={$borrow_repayment_result['borrow_id']}) and status=0");
        $this->db->trans_complete();
        if ($this->db->trans_status() == 1) {
            return 1;
        }
        return 1;
    }

    function user_borrow_total($user_id) {
        $sql = "select fstatus,account,repayment_account,repayment_yesaccount from zjy_borrow where user_id=$user_id";
        $query = $this->db->query($sql);
        $borrow_list = $query->result_array();
        $num0 = 0;
        $num1 = 0;
        $num2 = 0;
        $num3 = 0;
        foreach ($borrow_list as $borrow) {
            if ($borrow['fstatus'] == 3) {
                $num0++;
                if ($borrow['repayment_account'] != $borrow['repayment_yesaccount']) {
                    $num1++;
                } else {
                    $num3++;
                }
            } elseif ($borrow['fstatus'] == 2) {
                $num2++;
            }
        }
        $data['num0'] = $num0;
        $data['num1'] = $num1;
        $data['num2'] = $num2;
        $data['num3'] = $num3;
        return $data;
    }

    /**
     * 获取用户投标总额
     * @param $user_id
     */
    function tender_total($user_id) {
        $query = $this->db->query("select sum(account) as tender_total from zjy_borrow_tender where user_id=$user_id  and borrow_id in (select id from zjy_borrow where fstatus=3)");
        $result = $query->row_array();
        return $result['tender_total'];
    }

    /**
     * 获取用户已收总额
     * @param $user_id
     */
    function collection_total($user_id, $fstatus = 0) {
        //$query = $this->db->query("select sum(repay_account) as collection_total_account,sum(repay_account) as collection_total,sum(capital) as collection_capital,sum(interest) as collection_interest from zjy_borrow_collection where user_id=$user_id and fstatus=$fstatus and borrow_id in (select id from zjy_borrow where fstatus=3)");
        //return $query->row_array();
        $sql = "select sum(p1.repay_account) as collection_total_account,
			sum(p1.repay_account) as collection_total,
			sum(p1.capital) as collection_capital,
			sum(p1.interest) as collection_interest
			from zjy_borrow_collection as p1
			left join zjy_borrow as p2 on p1.borrow_id=p2.id
			left join zjy_borrow_tender as p3 on p1.tender_id=p3.id
			where p1.user_id=$user_id and p1.fstatus=$fstatus
			and p2.fstatus=3 and p3.transfer_status<3 ";
        $query = $this->db->query($sql);
        return $query->row_array();
    }

    /**
     * 获取用户当月已收总额
     * @param $user_id
     */
    function collection_month_total($user_id, $fstatus = 0) {
        $date = date('Y-m-') . '01';
        $start = strtotime($date);
        $end = time();
        $sql = "select sum(p1.repay_account) as collection_total_account,
			sum(p1.repay_account) as collection_total,
			sum(p1.capital) as collection_capital,
			sum(p1.interest) as collection_interest
			from zjy_borrow_collection as p1
			left join zjy_borrow as p2 on p1.borrow_id=p2.id
			left join zjy_borrow_tender as p3 on p1.tender_id=p3.id
			where p1.user_id=$user_id and p1.fstatus=$fstatus
			and p2.fstatus=3 and p3.transfer_status<3  and p1.add_time>=$start AND p1.add_time<=$end ";
        $query = $this->db->query($sql);
        return $query->row_array();
    }

    /**
     * 最近回款时间
     * @param $user_id
     */
    function first_collection_time($user_id) {
        $query = $this->db->query("select repay_time from zjy_borrow_collection where user_id=$user_id and fstatus=0  and borrow_id in (select id from zjy_borrow where fstatus=3) order by repay_time asc limit 1");
        $result = $query->row_array();
        if (count($result) > 0) {
            return $result['repay_time'];
        }
        return 0;
    }

    /**
     * 获取用户已收总额
     * @param $user_id
     */
    function repayment_total($user_id, $fstatus = -1) {
        $where = " where user_id=" . $user_id;
        if ($fstatus != -1) {
            $where .= " and fstatus=" . $fstatus;
        }
        $query = $this->db->query("select sum(repayment_account) as repayment_account,sum(repayment_yesaccount) as repayment_yesaccount,sum(repayment_account) as repayment_account from zjy_borrow_repayment $where");
        return $query->row_array();
    }

    /**
     * 借款户待还总额
     * @param $user_id
     * @param $fstatus
     */
    function loan_repayment_total($user_id, $fstatus = -1) {
        $where = " where borrow_id in (select id from zjy_borrow where user_id={$user_id} and fstatus=3) ";
        if ($fstatus != -1) {
            $where .= " and fstatus=" . $fstatus;
        }
        $sql = "select sum(repay_account) as repay_account,sum(capital) as capital_account,sum(interest) as interest_account from zjy_borrow_collection $where ";
        $query = $this->db->query($sql);
        $result = $query->row_array();
        return $result;
    }

    /**
     * 最近回款时间
     * @param $user_id
     */
    function first_repayment_time($user_id) {
        $query = $this->db->query("select repayment_account,repayment_time from zjy_borrow_repayment where user_id=$user_id and fstatus=0 order by repayment_time asc limit 1");
        return $query->row_array();
    }

    /**
     * 待收总额
     * @param $user_id
     */
    function collection_all_account() {
        $query = $this->db->query("select sum(repay_account) as collection_sum_account from
									zjy_borrow_collection where fstatus=1  and borrow_id in (select id from zjy_borrow where fstatus=3)");
        return $query->row_array();
    }

    /**
     * 待收总额
     * @param $user_id
     */
    function index_collection_all_account() {
        $mkey = "index_collection_all_account";
        $ret = $this->mycache->get($mkey);
        if ($ret != false) {
            return $ret;
        }
        $query = $this->db->query("select sum(repay_account) as collection_sum_account from
				zjy_borrow_collection where fstatus=1  and borrow_id in (select id from zjy_borrow where fstatus=3)");
        $result = $query->row_array();
        $this->mycache->set($mkey, $result['collection_sum_account'], 12 * 60 * 60);
        return $result['collection_sum_account'];
    }

    /*
     * 个人待收总额
     * @param int $userid
     * */
    function collection_account($userid){
        $query = $this->db->query("select sum(repay_account) as collection_sum_account
                                   from zjy_borrow_collection
                                   where fstatus=1  and borrow_id in (select id from zjy_borrow where fstatus=3) and user_id={$userid}") ;
        $result = $query->row_array();
        return $result['collection_sum_account'];
    }

    /*
     * 净值额度
     * */
    function net_amount($userid){
        $repayment = $this->collection_account($userid);
        //净值额度为待还款的80%
        return $repayment*0.8;
    }

    /**
     * 投标列表
     * @param unknown_type $data
     * @return unknown
     */
    function tenders_list($data) {
        $_where = " where 1=1 and p2.time_limit>3";
        if (isset($data['where']['strtime']) && $data['where']['strtime'] != 0) {
            $strtime = strtotime($data['where']['strtime'] . ' 00:00:00');
            $_where .= " and p1.add_time >= " . $strtime;
        }
        if (isset($data['where']['endtime']) && $data['where']['endtime'] != 0) {
            $endtime = strtotime($data['where']['endtime'] . ' 23:59:59');
            $_where .= " and p1.add_time <= " . $endtime;
        }
        $sql = "select p1.id,p1.user_id,p3.username,p1.account,p1.add_time,p1.fstatus,p2.id as borrow_id,
				p2.title,p2.time_limit,p2.is_day,p2.time_limit_day,p2.ftype
				from zjy_borrow_tender as p1 left join zjy_borrow as p2 on p1.borrow_id=p2.id
				left join zjy_user as p3 on p1.user_id=p3.user_id $_where order by p1.user_id,p2.time_limit,p2.id";
        $query = $this->db->query($sql);
        $tender_list = $query->result_array();
        return $tender_list;
    }

    /**
     * 回款排行榜
     * @param $data
     */
    function repayment_top($data = array()) {
        $_where = " where t1.fstatus=0 ";
        if (isset($data['where']['username']) && $data['where']['username'] != '') {
            $_where .= " and t2.username = '" . $data['where']['username'] . "'";
        }

        if (isset($data['where']['strtime']) && $data['where']['strtime'] != 0) {
            $strtime = strtotime($data['where']['strtime'] . ' 00:00:00');
            $_where .= " and t1.repay_time >= " . $strtime;
        }

        if (isset($data['where']['endtime']) && $data['where']['endtime'] != 0) {
            $endtime = strtotime($data['where']['endtime'] . ' 23:59:59');
            $_where .= " and t1.repay_time <= " . $endtime;
        }

        $sql = "SELECT t1.user_id,t2.username,SUM(t1.repay_account) AS rc FROM zjy_borrow_collection AS t1
				LEFT JOIN zjy_user AS t2 ON t1.user_id=t2.user_id $_where
				GROUP BY t1.user_id ORDER BY rc DESC LIMIT 0,10";
        $query = $this->db->query($sql);
        return $query->result_array();
    }

    /**
     * 未还的净值标总额
     * @param $user_id
     */
    function no_repayment_borrow_3($user_id) {
        $sql = "SELECT sum(p2.repayment_account) as money FROM zjy_borrow AS p1
				LEFT JOIN zjy_borrow_repayment AS p2 ON p1.id=p2.borrow_id
				WHERE p1.user_id={$user_id} AND p1.ftype=3 AND p2.fstatus=0";
        $query = $this->db->query($sql);
        $row = $query->row_array();
        if ($row['money'] == null) {
            return 0;
        }
        return $row['money'];
        /*
          $where = " where borrow_id in (select id from zjy_borrow where user_id={$user_id} and fstatus=3) ";
          if($fstatus != -1){
          $where .= " and fstatus=".$fstatus;
          }
          $sql = "select sum(repay_account) as repay_account,sum(capital) as capital_account,sum(interest) as interest_account from zjy_borrow_collection $where ";
          $query = $this->db->query($sql);
          $result = $query->row_array();
          return $result;
         */
    }

    /**
     * 获取用户净值标的最高罚息
     * @param $user_id
     */
    function jing_max_faxi($user_id) {
        $sql = "SELECT SUM(apr/12/30*time_limit_day*30*" . CON_LATE_RATE . "*account) as money FROM zjy_borrow
				WHERE user_id={$user_id} AND ftype=3 AND end_time>" . time();
        $query = $this->db->query($sql);
        $row = $query->row_array();
        if ($row['money'] == null) {
            return 0;
        }
        return round($row['money'], 2);
    }

    /**
     * 正在招标的净值标
     * @param $user_id
     */
    function now_borrow_3($user_id) {
        $sql = "select account from zjy_borrow where user_id={$user_id} and fstatus=1 limit 1";
        $query = $this->db->query($sql);
        $row = $query->row_array();
        if ($row['account'] == null) {
            return 0;
        }
        return $row['account'];
    }

    /**
     * 后台月统计
     */
    function admin_index() {
        $key = 'admin_borrow_index';
        $result = $this->mycache->get_array($key);
        if (!$result) {
            $result = array();
            /** 上个月 */
            //发标总额
            //$key = 'up_month_borrow';
            $start = strtotime("-1 month", strtotime(date('Y-m-01')));
            $end = strtotime(date("Y-m-01"));
            $sql = "select sum(account) as num from zjy_borrow where verify_time>={$start} and verify_time<{$end} and fstatus in(1,3)";
            $query = $this->db->query($sql);
            $row = $query->row_array();
            $result['up_month_borrow'] = $row['num'];

            //投标总额
            /*
              $sql = "select sum(account) as num from zjy_borrow_tender where add_time>={$start} and add_time<{$end} and fstatus=1";
              $query = $this->db->query($sql);
              $row = $query->row_array();
              $result['up_month_tender'] = $row['num'];
             */

            //线上充值统计
            $sql = "select sum(money) as num from zjy_account_recharge where ftype=1 and fstatus=1 and add_time>={$start} and add_time<{$end}";
            $query = $this->db->query($sql);
            $row = $query->row_array();
            $result['up_month_recharge'] = $row['num'];

            //回款统计
            $sql = "select sum(repay_yesaccount) as num from zjy_borrow_collection where fstatus=1 and repay_yestime>={$start} and repay_yestime<{$end}";
            $query = $this->db->query($sql);
            $row = $query->row_array();
            $result['up_month_repay'] = $row['num'];

            //线下充值奖励统计
            $type = RECHARGE_REWARD;
            $sql = "select sum(money) as num from zjy_account_log where ftype={$type} and add_time>={$start} and add_time<{$end}";
            $query = $this->db->query($sql);
            $row = $query->row_array();
            $result['up_month_recharge_reward'] = $row['num'];

            //投标奖励
            $type = AWARD_ADD;
            $sql = "select sum(money) as num from zjy_account_log where ftype={$type} and add_time>={$start} and add_time<{$end}";
            $query = $this->db->query($sql);
            $row = $query->row_array();
            $result['up_month_award_add'] = $row['num'];

            //回款续投奖励
            $type = REPAYMENT_TENDER_REWARD;
            $sql = "select sum(money) as num from zjy_account_log where ftype={$type} and add_time>={$start} and add_time<{$end}";
            $query = $this->db->query($sql);
            $row = $query->row_array();
            $result['up_month_xutou'] = $row['num'];


            //////////////////////////////////////////////////////
            //当月发标总额
            $start = strtotime(date("Y-m-01"));
            $end = time();
            $sql = "select sum(account) as num from zjy_borrow where verify_time>={$start} and verify_time<{$end} and fstatus in(1,3)";
            $query = $this->db->query($sql);
            $row = $query->row_array();
            $result['this_month_borrow'] = $row['num'];

            //当月投标总额
            /*
              $sql = "select sum(account) as num from zjy_borrow_tender where add_time>={$start} and add_time<{$end} and fstatus=1";
              $query = $this->db->query($sql);
              $row = $query->row_array();
              $result['this_month_tender'] = $row['num'];
             */

            //当月线上充值统计
            $sql = "select sum(money) as num from zjy_account_recharge where ftype=1 and fstatus=1 and add_time>={$start} and add_time<{$end}";
            $query = $this->db->query($sql);
            $row = $query->row_array();
            $result['this_month_recharge'] = $row['num'];

            //当月回款统计
            $sql = "select sum(repay_yesaccount) as num from zjy_borrow_collection where fstatus=1 and repay_yestime>={$start} and repay_yestime<{$end}";
            $query = $this->db->query($sql);
            $row = $query->row_array();
            $result['this_month_repay'] = $row['num'];

            //线下充值奖励统计
            $type = RECHARGE_REWARD;
            $sql = "select sum(money) as num from zjy_account_log where ftype={$type} and add_time>={$start} and add_time<{$end}";
            $query = $this->db->query($sql);
            $row = $query->row_array();
            $result['this_month_recharge_reward'] = $row['num'];

            //投标奖励
            $type = AWARD_ADD;
            $sql = "select sum(money) as num from zjy_account_log where ftype={$type} and add_time>={$start} and add_time<{$end}";
            $query = $this->db->query($sql);
            $row = $query->row_array();
            $result['this_month_award_add'] = $row['num'];

            //回款续投奖励
            $type = REPAYMENT_TENDER_REWARD;
            $sql = "select sum(money) as num from zjy_account_log where ftype={$type} and add_time>={$start} and add_time<{$end}";
            $query = $this->db->query($sql);
            $row = $query->row_array();
            $result['this_month_xutou'] = $row['num'];

            $this->mycache->set_array($key, $result, 3600 * 6);
        }
        return $result;
    }

    /**
     * 流转标的满标时间
     * @param $id
     */
    function lz_last_tender($id = 0) {
        if ($id > 0) {
            $key = "lz_last_tender_time_" . $id;
            //$this->mycache->delete($key);
            $ret = $this->mycache->get($key);
            if (!$ret) {
                $sql = "select add_time from zjy_borrow_tender where borrow_id={$id} order by id desc limit 1";
                $query = $this->db->query($sql);
                $row = $query->row_array();
                $ret = $row['add_time'];
                $this->mycache->set($key, $ret, 3600 * 24);
            }
            return $ret;
        } else {
            return false;
        }
    }

    /**
     * 获取用户净值标的最高罚息
     * @param $user_id
     */
    function user_first_flag($user_id) {
        $mode = $user_id % 100;
        $today = time() - 24 * 60 * 60;
        $sql = "SELECT count(*) as count FROM zjy_account_log_{$mode} WHERE user_id={$user_id} AND add_time<{$today} and ftype=" . COLLECTION;
        $query = $this->db->query($sql);
        $row = $query->row_array();
        if ($row['count'] == null) {
            return 0;
        }
        return $row['count'];
    }

    function user_first_tender($user_id) {
        $sql = 'SELECT * from zjy_borrow_tender where user_id = ' . $user_id . ' ORDER BY add_time asc limit 1';
        $query = $this->db->query($sql);
        return $query->row_array();
    }

    /* function verify(){
      $sql = "select user_id,id,title,verify_time,repayment_time from zjy_borrow"
      } */

    /**
     *
     * 投资者撤回投资
     */
    function borrow_review_single_false($data) {
        $this->load->model('Account_model');
        $borrow_tender_id = intval($data['id']);
        $ip = $data['ip'];
        $data['select'] = 1;
        $tender_obj = $this->get_borrow_tender_obj($borrow_tender_id, $data);

        $borrow = $this->get_borrow_obj($tender_obj['borrow_id']);
        if ($tender_obj && $tender_obj['fstatus'] != 3 && $borrow['ftype'] != 4) {
            $tender_obj['b_uid'] = $borrow['user_id'];
            $tender_obj['ip'] = $ip;
            $this->get_account_log($tender_obj);

            $this->db->query("update zjy_borrow_collection set fstatus=3 where tender_id={$tender_obj['id']}");
            $this->db->query("update zjy_borrow_tender set fstatus=3 where id={$tender_obj['id']}");

            //更新投标表(借到的资金和投标的次数)
            $this->db->query("update zjy_borrow set account_yes=account_yes-{$tender_obj['account']},tender_times=tender_times-1 where id={$borrow['id']}");
            return 1;
        } else {
            return 0;
        }
    }

    function get_account_log($tmp) {
        $mode = $tmp['user_id'] % 100;
        $user_account = $this->Account_model->get_account($tmp['user_id']);
        $log['user_id'] = $tmp['user_id'];
        $log['ftype'] = INVEST_SINGLE_FALSE;
        $log['money'] = $tmp['account']; //投资者投标金额
        $log['total'] = $user_account['total']; //账户总额
        $log['use_money'] = $user_account['use_money'] + $log['money']; //可用金额+投资者投标金额
        $log['no_use_money'] = $user_account['no_use_money'] - $log['money']; //冻结资金-投资者投标金额
        $log['collection'] = $user_account['collection']; //待收金额
        $log['to_user'] = $tmp['b_uid']; //招标者ID
        $log['remark'] = "单个撤标返回的投标额";
        $log['add_time'] = time();
        $log['addip'] = $tmp['ip'];
        $this->db->insert('zjy_account_log_' . $mode, $log);
        $set_account = "use_money=use_money+{$log['money']},no_use_money=no_use_money-{$log['money']}";
        $this->db->query("update zjy_account set {$set_account} where user_id={$tmp['user_id']}");
    }

    function get_count_auto_tender() {
        $key = 'auto_tender_count';
        $this->mycache->delete($key);
        $num = $this->mycache->get($key);

        $valid = strtotime('2014-04-17 10:00:00') + 2 * 3600 * 24;
        $now = time();

        if (!$num) {
            $sql = "SELECT COUNT(*) as num FROM zjy_borrow_auto WHERE fstatus=1 AND is_del=0";

            if ($now > $valid) {
                $sql .= " AND valid_start_time<{$now} AND valid_end_time>{$now}";
            }

            $query = $this->db->query($sql);
            $row = $query->row_array();
            $num = $row['num'];
            $this->mycache->set($key, $num, 900);
        }
        return $num;
    }

    function borrow_sl_tender($data = array()) {
        $id = $data['id'];
        $ip = $data['ip'];
        $user_id = $data['user_id'];
        $money = $data['money'];
        $account = $data['account'];
        $borrow = self::get_borrow_obj($data['id']);
        $this->load->model('Account_model');
        $this->load->model('User_model');
        $this->load->model('Message_model');
        $this->load->model('Credit_model');
        $borrow_url = "<a href='/borrow/slobj/{$borrow['id']}.html' target=_blank>{$borrow['title']}</a>";
        $this->db->trans_start();
        //第一次投标，更新标状态和复审时间复审备注
        if ($borrow['tender_times'] < 1) {
            $this->db->query("update zjy_borrow set fstatus=3,repayment_time=" . time() . ",repayment_remark='自动复审' where id={$borrow['id']}");
        }
        //更新投标次数和已借入金额
        $this->db->query("update zjy_borrow set account_yes=account_yes+{$data['account']},tender_times=tender_times+1  where id='{$borrow['id']}'");
        //新增投标记录
        $t2data['add_time'] = time();
        $t2data['addip'] = $ip;
        $t2data['user_id'] = $user_id;
        $t2data['borrow_id '] = $id;
        $t2data['money'] = $money;
        $t2data['account'] = $account;
        $t2data['fstatus'] = 1;
        $this->db->insert('zjy_borrow_tender', $t2data);
        $tender_id = $this->db->insert_id();

        if ($tender_id > 0) {
            $eq['account'] = $account;
            $eq['apr'] = $borrow['apr'];
            $eq['time_limit'] = $borrow['time_limit'];
            $eq['style'] = $borrow['style'];
            $eq['is_day'] = $borrow['is_day'];
            $eq['time_limit_day'] = $borrow['time_limit_day'];
            $result = equal_interest($eq);
            $_repay_time = time() + $borrow['time_limit_day'] * 60 * 60 * 24;
            $repayment_account = 0;
            //添加待收明细
            foreach ($result as $key => $value) {
                $repayment_account += $value['repayment_account'];
                //将归还信息写进去
                $this->db->query("insert into zjy_borrow_collection set user_id=$user_id,borrow_id=$id,add_time=" . time() . ",addip='{$ip}',
						`tender_id`='{$tender_id}',`forder`='{$key}',`repay_time`='{$_repay_time}',
						`repay_account`='{$value['repayment_account']}',`interest`='{$value['interest']}',
						`capital`='{$value['capital']}'");
            }
            $_interest = round($repayment_account - $data['account'], 2);
            $this->db->query(" update zjy_borrow_tender set repayment_account='{$repayment_account}',
								wait_account ='{$repayment_account}',interest = '{$_interest}',
								wait_interest = '{$_interest}' where id={$tender_id}");

            //投标金额冻结
            $mode = $user_id % 100;
            $account_result = $this->Account_model->get_account($user_id);
            $log['user_id'] = $user_id;
            $log['ftype'] = TENDER;
            $log['money'] = $account;
            $log['total'] = $account_result['total'];
            $log['use_money'] = $account_result['use_money'] - $log['money'];
            $log['no_use_money'] = $account_result['no_use_money'] + $log['money'];
            $log['collection'] = $account_result['collection'];
            $log['to_user'] = $borrow['user_id'];
            $log['remark'] = "投标冻结资金";
            $log['add_time'] = time();
            $log['addip'] = $ip;
            $this->db->insert('zjy_account_log_' . $mode, $log);
            $this->db->query("update zjy_account set use_money=use_money-{$log['money']},no_use_money=no_use_money+{$log['money']} where user_id={$user_id}");


            //扣除投资者的金钱。
            unset($account_result);
            unset($log);
            $account_result = $this->Account_model->get_account($user_id);
            $log['user_id'] = $user_id;
            $log['ftype'] = INVEST;
            $log['money'] = $account;
            $log['total'] = $account_result['total'] - $log['money'];
            $log['use_money'] = $account_result['use_money'];
            $log['no_use_money'] = $account_result['no_use_money'] - $log['money'];
            $log['collection'] = $account_result['collection'];
            $log['to_user'] = $borrow['user_id'];
            $log['remark'] = "投标成功费用扣除";
            $log['add_time'] = time();
            $log['addip'] = $ip;
            $this->db->insert('zjy_account_log_' . $mode, $log);
            $this->db->query("update zjy_account set total=total-{$log['money']},no_use_money=no_use_money-{$log['money']} where user_id={$user_id}");


            //添加待收的金额
            unset($account_result);
            unset($log);
            $account_result = $this->Account_model->get_account($user_id);
            $log['user_id'] = $user_id;
            $log['ftype'] = COLLECTION;
            $log['money'] = $repayment_account;
            $log['total'] = $account_result['total'] + $log['money'];
            $log['use_money'] = $account_result['use_money'];
            $log['no_use_money'] = $account_result['no_use_money'];
            $log['collection'] = $account_result['collection'] + $log['money'];
            $log['to_user'] = $borrow['user_id'];
            $log['remark'] = "待收金额";
            $log['add_time'] = time();
            $log['addip'] = $ip;
            $this->db->insert('zjy_account_log_' . $mode, $log);
            $this->db->query("update zjy_account set total=total+{$log['money']},collection=collection+{$log['money']} where user_id={$user_id}");

            //提醒设置
            $this->Message_model->send(array('sent_user' => 1, 'receive_user' => $user_id,
                'name' => "投资的标[<font color=red>{$borrow['title']}</font>投标成功",
                'fstatus' => 0, 'message_type' => 'system', 'sented' => 0, 'deltype' => 0,
                'content' => "你所投资的标[<a href='/borrow/slobj/{$id}.html' target=_blank><font color=red>{$borrow['title']}</font></a>]在" . date("Y-m-d", time()) . "已经通过",
                'add_time' => time(), 'addip' => $ip));

            /* if ($borrow['is_day']==1){
              $credit_value = round($account/100*$borrow['apr']/100*($borrow['time_limit_day']/30));
              }else{
              $credit_value = round($account/100*$borrow['apr']/100*$borrow['time_limit']);
              }

              //增加积分
              $creditNidType = $this->Credit_model->arrays('creditNidType');
              $creditTypeName = $this->Credit_model->arrays('creditTypeName');
              $credit_log = array('user_id'=>$user_id,
              'type_id'=>$creditNidType['invest_success'],
              'op'=>1,
              'credit_value'=>$credit_value,
              'remark'=>$creditTypeName[$creditNidType['invest_success']].'加'.$credit_value.'分',
              'op_user'=>$borrow['user_id'],
              'add_time'=>time(),
              'addip'=>$ip);
              $this->Credit_model->incr_credit($credit_log); */

            //借款者总金额增加。
            unset($account_result);
            unset($log);
            $mode1 = $borrow['user_id'] % 100;
            $account_result = $this->Account_model->get_account($borrow['user_id']);
            $log['user_id'] = $borrow['user_id'];
            $log['ftype'] = BORROW_SUCCESS;
            $log['money'] = $account;
            $log['total'] = $account_result['total'] + $log['money'];
            $log['use_money'] = $account_result['use_money'] + $log['money'];
            $log['no_use_money'] = $account_result['no_use_money'];
            $log['collection'] = $account_result['collection'];
            $log['to_user'] = "0";
            $log['remark'] = "通过[{$borrow_url}]借到的款";
            $log['add_time'] = time();
            $log['addip'] = $ip;
            $this->db->insert('zjy_account_log_' . $mode1, $log);
            $this->db->query("update zjy_account set total=total+{$log['money']},use_money=use_money+{$log['money']} where user_id={$borrow['user_id']}");

            //冻结借款标的保证金10%。
            unset($account_result);
            unset($log);
            $account_result = $this->Account_model->get_account($borrow['user_id']);
            $log['user_id'] = $borrow['user_id'];
            $log['ftype'] = MARGIN;
            $log['money'] = $data['account'] * 0.1;
            $log['total'] = $account_result['total'];
            $log['use_money'] = $account_result['use_money'] - $log['money'];
            $log['no_use_money'] = $account_result['no_use_money'] + $log['money'];
            $log['collection'] = $account_result['collection'];
            $log['to_user'] = "0";
            $log['remark'] = "冻结借款标的[{$borrow_url}]的保证金";
            $log['add_time'] = time();
            $log['addip'] = $ip;
            //如果保证金等于0，那不在写记录了
            if ($log['money'] <> 0) {
                $this->db->insert('zjy_account_log_' . $mode1, $log);
                $this->db->query("update zjy_account set use_money=use_money-{$log['money']},no_use_money=no_use_money+{$log['money']} where user_id={$borrow['user_id']}");
                //更新保证金
                $this->db->query("update zjy_borrow set forst_account=forst_account+{$log['money']} where id='{$borrow['id']}'");
            }

            //借款手续费
            unset($account_result);
            unset($log);
            $borrow_fee = 0;
            $borrow_fee = round($borrow['time_limit'] * 0.005 * $account, 2);
            $account_result = $this->Account_model->get_account($borrow['user_id']);
            $log['user_id'] = $borrow['user_id'];
            $log['ftype'] = BORROW_FEE;
            $log['money'] = $borrow_fee;
            $log['total'] = $account_result['total'] - $log['money'];
            $log['use_money'] = $account_result['use_money'] - $log['money'];
            $log['no_use_money'] = $account_result['no_use_money'];
            $log['collection'] = $account_result['collection'];
            $log['to_user'] = "0";
            $log['remark'] = "借款[{$borrow_url}]的手续费";
            $log['add_time'] = time();
            $log['addip'] = $ip;
            $this->db->insert('zjy_account_log_' . $mode1, $log);
            $this->db->query("update zjy_account set total=total-{$log['money']},use_money=use_money-{$log['money']} where user_id={$borrow['user_id']}");

            $nowtime = time();
            $endtime = time() + $borrow['time_limit_day'] * 60 * 60 * 24;
            $_each_time = date('m月d日', $endtime);
            $this->db->query("update zjy_borrow set success_time='{$nowtime}',end_time='{$endtime}',each_time='{$_each_time}',
					 			payment_account=payment_account+'{$repayment_account}'
					 			where id='{$borrow['id']}'");


            //如果有设置奖励并且招标成功
            if ($borrow['award'] == 2 || $borrow['funds'] > 0) {
                //投标奖励扣除和增加。
                $money = round((($borrow['funds'] / 100) * $account), 2);

                unset($account_result);
                unset($log);
                $account_result = $this->Account_model->get_account($user_id);
                $log['user_id'] = $user_id;
                $log['ftype'] = AWARD_ADD;
                $log['money'] = $money;
                $log['total'] = $account_result['total'] + $log['money'];
                $log['use_money'] = $account_result['use_money'] + $log['money'];
                $log['no_use_money'] = $account_result['no_use_money'];
                $log['collection'] = $account_result['collection'];
                $log['to_user'] = $borrow['user_id'];
                $log['remark'] = "借款[{$borrow_url}]的奖励";
                $log['add_time'] = time();
                $log['addip'] = $ip;
                $this->db->insert('zjy_account_log_' . $mode, $log);
                $this->db->query("update zjy_account set total=total+{$log['money']},use_money=use_money+{$log['money']} where user_id={$user_id}");

                unset($account_result);
                unset($log);
                $account_result = $this->Account_model->get_account($borrow['user_id']);
                $log['user_id'] = $borrow['user_id'];
                $log['ftype'] = AWARD_LOWER;
                $log['money'] = $money;
                $log['total'] = $account_result['total'] - $log['money'];
                $log['use_money'] = $account_result['use_money'] - $log['money'];
                $log['no_use_money'] = $account_result['no_use_money'];
                $log['collection'] = $account_result['collection'];
                $log['to_user'] = $user_id;
                $log['remark'] = "扣除借款[{$borrow_url}]的奖励";
                $log['add_time'] = time();
                $log['addip'] = $ip;
                $this->db->insert('zjy_account_log_' . $mode1, $log);
                $this->db->query("update zjy_account set total=total-{$log['money']},use_money=use_money-{$log['money']} where user_id={$borrow['user_id']}");
            }

            $this->db->trans_complete();

            if ($this->db->trans_status() == 1) {
//				$protocolMailKey = "protocolMailKey";
//				$mailList = $this->mycache->get_array($protocolMailKey);
//				$mailList = $mailList ? $mailList : array();
//				$mailList[] = array(
//					'user_id' => $user_id,
//					'borrow_id' => $id,
//					'borrow_title' => $borrow['title'],
//					'tender_id' => $tender_id
//				);
//				$this->mycache->set_array($protocolMailKey,$mailList);
                return 1;
            }
        } else {
            $this->db->trans_rollback();
            return 0;
        }
    }

    /**
     * 流转标撤销投标
     */
    function tender_cancel($id) {

        $this->load->model('Account_model');
        $this->db->where('id', $id);
        $query = $this->db->get('zjy_borrow_tender');
        $tender = $query->row_array();
        $time = time();
        $ip = $this->js->get_ip();

        if (isset($tender['id']) && $tender['fstatus'] == 1) {
            if ($tender['repayment_yesaccount'] > 0) {
                return '该投资部分已还，不能撤销';
            } else {

                $this->db->trans_start();
                $mode = $tender['user_id'] % 100;

                //撤销投标待收扣除
                $account_result = $this->Account_model->get_account($tender['user_id']);
                $log['user_id'] = $tender['user_id'];
                $log['ftype'] = INVEST_CANCEL_COLL;
                $log['money'] = $tender['repayment_account'];
                $log['total'] = $account_result['total'] - $log['money'];
                $log['use_money'] = $account_result['use_money'];
                $log['no_use_money'] = $account_result['no_use_money'];
                $log['collection'] = $account_result['collection'] - $log['money'];
                $log['to_user'] = "0";
                $log['remark'] = "撤销投标待收扣除";
                $log['add_time'] = $time;
                $log['addip'] = $ip;
                $this->db->insert('zjy_account_log_' . $mode, $log);
                $this->db->query("update zjy_account set total=total-{$log['money']},collection=collection-{$log['money']} where user_id={$tender['user_id']}");
                unset($log);

                //撤销投标本金返回
                $account_result = $this->Account_model->get_account($tender['user_id']);
                $log['user_id'] = $tender['user_id'];
                $log['ftype'] = INVEST_CANCEL_ACC;
                $log['money'] = $tender['account'];
                $log['total'] = $account_result['total'] + $log['money'];
                $log['use_money'] = $account_result['use_money'] + $log['money'];
                $log['no_use_money'] = $account_result['no_use_money'];
                $log['collection'] = $account_result['collection'];
                $log['to_user'] = "0";
                $log['remark'] = "撤销投标本金返回";
                $log['add_time'] = $time;
                $log['addip'] = $ip;
                $this->db->insert('zjy_account_log_' . $mode, $log);
                $this->db->query("update zjy_account set total=total+{$log['money']},use_money=use_money+{$log['money']} where user_id={$tender['user_id']}");
                unset($log);

                //撤销投标奖励扣除
                $this->db->where('id', $tender['borrow_id']);
                $query = $this->db->get('zjy_borrow');
                $borrow = $query->row_array();
                if ($borrow['funds'] > 0) {
                    $money = round((($borrow['funds'] / 100) * $tender['account']), 2);
                    $account_result = $this->Account_model->get_account($tender['user_id']);
                    $log['user_id'] = $tender['user_id'];
                    $log['ftype'] = INVEST_CANCEL_AWARD;
                    $log['money'] = $money;
                    $log['total'] = $account_result['total'] - $log['money'];
                    $log['use_money'] = $account_result['use_money'] - $log['money'];
                    $log['no_use_money'] = $account_result['no_use_money'];
                    $log['collection'] = $account_result['collection'];
                    $log['to_user'] = "0";
                    $log['remark'] = "撤销投标奖励扣除";
                    $log['add_time'] = $time;
                    $log['addip'] = $ip;
                    $this->db->insert('zjy_account_log_' . $mode, $log);
                    $this->db->query("update zjy_account set total=total-{$log['money']},use_money=use_money-{$log['money']} where user_id={$tender['user_id']}");
                    unset($log);
                }

                //如果此次投标有用到体验金  则扣除体验金
                $sql = "SELECT SUM(exp_money) AS expmoney FROM zjy_expmoney_deduct WHERE collection_id IN(SELECT id FROM zjy_borrow_collection WHERE tender_id={$id})";
                $query = $this->db->query($sql);
                $tmpRow = $query->row_array();
                $expMoney = $tmpRow['expmoney'] ? $tmpRow['expmoney'] : 0;
                if ($expMoney > 0) {
                    //扣除体验金
                    $account_result = $this->Account_model->get_account($tender['user_id']);
                    $log['user_id'] = $tender['user_id'];
                    $log['ftype'] = EXP_MONEY_DEDUCT;
                    $log['money'] = $expMoney;
                    $log['total'] = $account_result['total'] - $log['money'];
                    $log['use_money'] = $account_result['use_money'] - $log['money'];
                    $log['no_use_money'] = $account_result['no_use_money'];
                    $log['collection'] = $account_result['collection'];
                    $log['to_user'] = "0";
                    $log['remark'] = "撤销投标扣除返回的体验金";
                    $log['add_time'] = $time;
                    $log['addip'] = $ip;
                    $this->db->insert('zjy_account_log_' . $mode, $log);
                    $this->db->query("update zjy_account set total=total-{$log['money']},use_money=use_money-{$log['money']} where user_id={$tender['user_id']}");
                    $this->db->query("delete from zjy_expmoney_deduct WHERE collection_id IN(SELECT id FROM zjy_borrow_collection WHERE tender_id={$id})");
                    unset($log);
                }



                /*                 * ******* 流转标额度不空出，用内部账户填补 ************* */
                $tuid = 329;
                $tmpTender = $tender;
                unset($tmpTender['id']);
                $tmpTender['user_id'] = $tuid;
                $tmpTender['add_time'] = $time;
                $this->db->insert('zjy_borrow_tender', $tmpTender);
                $new_tender_id = $this->db->insert_id();

                //投标金额冻结
                $mode = $tuid % 100;
                $account_result = $this->Account_model->get_account($tuid);
                $log['user_id'] = $tuid;
                $log['ftype'] = TENDER;
                $log['money'] = $tender['account'];
                $log['total'] = $account_result['total'];
                $log['use_money'] = $account_result['use_money'] - $log['money'];
                $log['no_use_money'] = $account_result['no_use_money'] + $log['money'];
                $log['collection'] = $account_result['collection'];
                $log['to_user'] = $borrow['user_id'];
                $log['remark'] = "投标冻结资金";
                $log['add_time'] = $time;
                $log['addip'] = $ip;
                $this->db->insert('zjy_account_log_' . $mode, $log);
                $this->db->query("update zjy_account set use_money=use_money-{$log['money']},no_use_money=no_use_money+{$log['money']} where user_id={$tuid}");

                //扣除投资者的金钱。
                unset($log);
                $account_result = $this->Account_model->get_account($tuid);
                $log['user_id'] = $tuid;
                $log['ftype'] = INVEST;
                $log['money'] = $tender['account'];
                $log['total'] = $account_result['total'] - $log['money'];
                $log['use_money'] = $account_result['use_money'];
                $log['no_use_money'] = $account_result['no_use_money'] - $log['money'];
                $log['collection'] = $account_result['collection'];
                $log['to_user'] = $borrow['user_id'];
                $log['remark'] = "投标成功费用扣除";
                $log['add_time'] = $time;
                $log['addip'] = $ip;
                $this->db->insert('zjy_account_log_' . $mode, $log);
                $this->db->query("update zjy_account set total=total-{$log['money']},no_use_money=no_use_money-{$log['money']} where user_id={$tuid}");

                //添加待收的金额
                unset($log);
                $account_result = $this->Account_model->get_account($tuid);
                $log['user_id'] = $tuid;
                $log['ftype'] = COLLECTION;
                $log['money'] = $tender['repayment_account'];
                $log['total'] = $account_result['total'] + $log['money'];
                $log['use_money'] = $account_result['use_money'];
                $log['no_use_money'] = $account_result['no_use_money'];
                $log['collection'] = $account_result['collection'] + $log['money'];
                $log['to_user'] = $borrow['user_id'];
                $log['remark'] = "待收金额";
                $log['add_time'] = $time;
                $log['addip'] = $ip;
                $this->db->insert('zjy_account_log_' . $mode, $log);
                $this->db->query("update zjy_account set total=total+{$log['money']},collection=collection+{$log['money']} where user_id={$tuid}");

                //待收明细改成补标人的
                $sql = "update zjy_borrow_collection set user_id={$tuid},tender_id={$new_tender_id} where tender_id={$id}";
                $this->db->query($sql);
                //原投标记录表状态-取消
                $sql = "update zjy_borrow_tender set fstatus=2 where id={$id}";
                $this->db->query($sql);

                $this->db->trans_complete();
                if ($this->db->trans_status() == 1) {
                    return '操作成功';
                } else {
                    return '操作失败';
                }
            }
        } else {
            return '数据错误';
        }
    }

    function guarantee_add($data) {
        $this->db->insert('zjy_borrow_guarantee', $data);
        $this->mycache->delete('get_guarantee_borrow_list');
        $this->mycache->delete('zjy_guarantee_name_list');
        return $this->db->insert_id();
    }

    function guarantee_update($id, $data) {
        $this->db->where('id', $id);
        $this->db->update('zjy_borrow_guarantee', $data);
        $this->mycache->delete('get_guarantee_borrow_list');
        $this->mycache->delete('zjy_guarantee_name_list');
        return $this->db->affected_rows();
    }

    function get_guarantee_borrow_list() {
        $mkey = "get_guarantee_borrow_list";

        $ret = $this->mycache->get_array($mkey);
        if ($ret != false) {
            return $ret;
        }

        $select = " id, name, type, alias, isActive ";

        //封装条件
        $_where = " where is_del=0 ";

        //排序
        $_order = " order by id desc ";

        //封装sql
        $sql_result = "select $select from zjy_borrow_guarantee ";
        $sql_result .= $_where;
        $sql_result .= $_order;

        $query = $this->db->query($sql_result);
        $borrow_guarantee_list = $query->result_array();
        if (count($borrow_guarantee_list) < 1) {
            return array();
        }
        $this->mycache->set_array($mkey, $borrow_guarantee_list);
        return $borrow_guarantee_list;
    }

    function get_guarantee_list($parms = array(), $per_page = 0, $page_size = 20) {
        $tmp = array();
        foreach ($parms as $key => $val) {
            if (is_string($key) && $key == 'is_del') {
                $tmp[] = "`{$key}` = '{$val}'";
            }

            if ($val) {
                if (is_numeric($key)) {
                    $tmp[] = $val;
                } else {
                    $tmp[] = $key == 'name' ? "`{$key}` like '%{$val}%'" : $tmp[] = "`{$key}` = '{$val}'";
                }
            }
        }
        $select = "*";
        $where = '';
        $tmp && $where = " where " . implode(' and ', $tmp);
        $order = "order by id asc";
        $limit = " limit {$per_page},{$page_size}";
        $sql = "select {$select} from zjy_borrow_guarantee {$where} {$order} {$limit}";
        $query = $this->db->query($sql);
        $data['list'] = $query->result_array();
        $sql = "select count(*) as count from zjy_borrow_guarantee {$where}";
        $query = $this->db->query($sql);
        $data['count'] = $query->row()->count;
        return $data;
    }

    function get_borrow_guarantee_obj($id) {
        $select = "*";
        $this->db->select($select);
        $this->db->where('id', $id);
        $query = $this->db->get('zjy_borrow_guarantee');
        return $query->row_array();
    }

    function get_guarantee_name_list() {
        $key = 'zjy_guarantee_name_list';
        $list = $this->mycache->get_array($key);
        if (!$list) {
            $this->db->select('id,name');
            $query = $this->db->get('zjy_borrow_guarantee');
            $result = $query->result_array();
            $list = array();
            if ($result) {
                foreach ($result as $v) {
                    $list[$v['id']] = $v['name'];
                }
                $this->mycache->set_array($key, $list);
            }
        }
        return $list;
    }

    function get_borrow_comment_list($parms = array(), $per_page = 0, $page_size = 20) {
        $select = "*";
        $where = ' where 1=1 ';

        if (isset($parms['borrow_id']) && $parms['borrow_id'] != '') {
            $where .= " and b.borrow_id = " . $parms['borrow_id'];
        }

        if (isset($parms['status']) && $parms['status'] > 0) {
            $where .= " and b.status = " . $parms['status'];
        }

        $select = "b.*,u.username";

        $order = "order by b.add_time desc";


        $sqlcount = "select count(*) as count from zjy_borrow_comment as b {$where}";
        $queryc = $this->db->query($sqlcount);
        $data['count'] = $queryc->row()->count;

        $sql = "select {$select} from zjy_borrow_comment as b left join zjy_user as u on b.user_id=u.user_id {$where} {$order}";

        if (isset($parms['limit']) && $parms['limit'] == 'all') {
            $query = $this->db->query($sql);
            $data['list'] = $query->result_array();
            return $data;
        } else {
            $sql .= " limit {$per_page},{$page_size}";
            $query = $this->db->query($sql);
            $data['list'] = $query->result_array();

            return $data;
        }
    }

    function borrow_comment_add($data) {
        $this->db->insert('zjy_borrow_comment', $data);
        return $this->db->insert_id();
    }

    /**
     * 用户自动投标列表
     * @param $data
     */
    function get_borrow_collection($data) {
        //封装查询内容
        $select = "t1.*,t2.mmm_id";

        //封装条件
        $_where = " where 1=1 ";
        //哪个标?
        if (isset($data['where']['borrow_id']) && $data['where']['borrow_id'] != '') {
            $_where .= " and t1.borrow_id = " . $data['where']['borrow_id'];
        }
        //哪一期?
        if (isset($data['where']['forder']) && $data['where']['forder'] != '') {
            $_where .= " and t1.forder = " . $data['where']['forder'];
        }

        //封装sql
        $sql_result = "select $select from zjy_borrow_collection as t1 left join zjy_user as t2 on t1.user_id=t2.user_id ";
        $sql_result .= $_where;
        $query = $this->db->query($sql_result);
        return $query->result_array();
    }

    /**
     * 后台统计汇总
     */
    function admin_total_index() {

        //$endtime = strtotime(date('Y-m-d'));

        /*         * *********************************************************************** */
        //成功借出总额
        $sql = "select sum(account) as num from zjy_borrow where fstatus in(1,3) and user_id not in (select user_id from zjy_user where is_self=1)";
        $query = $this->db->query($sql);
        $row = $query->row_array();
        $result['up_borrow'] = $row['num'];

        //投标总额
        /* $sql_tender = "select sum(account) as num from zjy_borrow_tender where fstatus=1 and user_id not in (select user_id from zjy_user where is_self=1)";
          $query_tender = $this->db->query($sql_tender);
          $row_tender = $query_tender->row_array();
          $result['up_tender'] = $row_tender['num']; */

        //成功借款利息总额
        $sqliterest = "select sum(repayment_account-account) as num from zjy_borrow where  fstatus in(1,3) and user_id not in(select user_id from zjy_user where is_self=1)";
        $query = $this->db->query($sqliterest);
        $row = $query->row_array();
        $result['up_iterest'] = $row['num'];

        //线上充值统计
        $sql_online = "select sum(money) as num from zjy_account_recharge where ftype=1 and fstatus=1 and user_id not in (select user_id from zjy_user where is_self=1)";
        $query_online = $this->db->query($sql_online);
        $row_online = $query_online->row_array();
        $result['up_recharge'] = $row_online['num'];

        //平台充值统计
        $sql_plat = "select sum(money) as num from zjy_account_recharge where ftype=0 and fstatus=1 and user_id not in (select user_id from zjy_user where is_self=1)";
        $query_plat = $this->db->query($sql_plat);
        $row_plat = $query_plat->row_array();
        $result['up_plat_recharge'] = $row_plat['num'];

        //提现总额
        $sql_tx = "SELECT SUM(total) as tx FROM zjy_account_cash WHERE fstatus IN(1,4) and user_id not in (select user_id from zjy_user where is_self=1)";
        $query_tx = $this->db->query($sql_tx);
        $row_tx = $query_tx->row_array();
        $result['up_tx'] = $row_tx['tx'];

        //提现手续费
        $sql_txfee = "SELECT SUM(fee) as tx FROM zjy_account_cash WHERE fstatus IN(1,4) and user_id not in(select user_id from zjy_user where is_self=1)";
        $query_txfee = $this->db->query($sql_txfee);
        $row_txfee = $query_txfee->row_array();
        $result['up_txfee'] = $row_txfee['tx'];


        //已还款总额
        $sql_repyament = "select sum(repay_yesaccount) as num from zjy_borrow_collection where fstatus=1 and user_id not in (select user_id from zjy_user where is_self=1)";
        $query_repayment = $this->db->query($sql_repyament);
        $row_repayment = $query_repayment->row_array();
        $result['up_repay'] = $row_repayment['num'];

        //冻结中的保证金总额
        $sql = "select sum(forst_account) as forst_money from zjy_borrow where fstatus in(1,3) and user_id not in (select user_id from zjy_user where is_self=1)";
        $query = $this->db->query($sql);
        $row = $query->row_array();
        $result['up_forst'] = $row['forst_money'];

        //投标奖励
        $type = AWARD_ADD;
        $sql_awardadd = "select sum(money) as num from zjy_account_log where ftype={$type} and user_id not in (select user_id from zjy_user where is_self=1)";
        $query_awardadd = $this->db->query($sql_awardadd);
        $row_award = $query_awardadd->row_array();
        $result['up_award_add'] = $row_award['num'];


        //未还款总额
        $sql_collection = "select sum(repay_account) as collection from zjy_borrow_collection where fstatus=0 and user_id not in (select user_id from zjy_user where is_self=1)";
        $query_collection = $this->db->query($sql_collection);
        $row_collection = $query_collection->row_array();
        $result['up_collection'] = $row_collection['collection'];

        //邀请奖励
        $type = INVITE_REWARD;
        $sql_awardadd = "select sum(money) as num from zjy_account_log where ftype={$type} and user_id not in (select user_id from zjy_user where is_self=1)";
        $query_awardadd = $this->db->query($sql_awardadd);
        $row_award = $query_awardadd->row_array();
        $result['up_award_invite'] = $row_award['num'];

        //借款管理费
        $type = BORROW_FEE;
        $sql = "select sum(money) as num from zjy_account_log where ftype={$type} and user_id not in (select user_id from zjy_user where is_self=1)";
        $query = $this->db->query($sql);
        $row = $query->row_array();
        $result['up_borrow_fee'] = $row['num'];

        //投资管理费=利息管理费用=居间服务费
        $jjtype = TENDER_MANGE;
        $sql_jj = "select sum(money) as num from zjy_account_log where ftype={$jjtype} and user_id not in(select user_id from zjy_user where is_self=1)";
        $query_jj = $this->db->query($sql_jj);
        $row_jj = $query_jj->row_array();
        $result['up_jujian'] = $row_jj['num'];

        //VIP费用总额
        $type = VIP; //VIP收费
        $sql = "select sum(money) as num from zjy_account_log where ftype={$type} and user_id not in(select user_id from zjy_user where is_self=1)";
        $query = $this->db->query($sql);
        $row = $query->row_array();
        $vip_money = $row['num'] ? $row['num'] : 0;
        $type = VIP_REPAY; //VIP费用返还
        $sql = "select sum(money) as num from zjy_account_log where ftype={$type} and user_id not in(select user_id from zjy_user where is_self=1)";
        $query = $this->db->query($sql);
        $row = $query->row_array();
        $vip_back_money = $row['num'] ? $row['num'] : 0;
        $result['up_vip_money'] = $vip_money - $vip_back_money;



        //会员总数
        $sqluser = "select count(user_id) as num from zjy_user where user_id not in(select user_id from zjy_user where is_self=1)";
        $queryuser = $this->db->query($sqluser);
        $row = $queryuser->row_array();
        $result['up_user_num'] = $row['num'];

        //VIP总数
        $sqluservip = "select count(user_id) as num from zjy_user_vip where vip_status = 1 and user_id not in(select user_id from zjy_user where is_self=1)";
        $queryvip = $this->db->query($sqluservip);
        $rowvip = $queryvip->row_array();
        $result['up_vip_num'] = $rowvip['num'];

        //身份认证
        $sqluserreal = "select count(user_id) as num from zjy_user where real_status = 1 and user_id not in(select user_id from zjy_user where is_self=1)";
        $queryreal = $this->db->query($sqluserreal);
        $rowreal = $queryreal->row_array();
        $result['up_real_num'] = $rowreal['num'];


        //手机认证
        $sqluserphone = "select count(user_id) as num from zjy_user where phone_status = 1 and user_id not in(select user_id from zjy_user where is_self=1)";
        $queryphone = $this->db->query($sqluserphone);
        $rowphone = $queryphone->row_array();
        $result['up_phone_num'] = $rowphone['num'];

        //EMAIL认证
        $sqluseremail = "select count(user_id) as num from zjy_user where email_status = 1 and user_id not in(select user_id from zjy_user where is_self=1)";
        $queryemail = $this->db->query($sqluseremail);
        $rowemail = $queryemail->row_array();
        $result['up_email_num'] = $rowemail['num'];

        //投资人总数
        /* $sql_user_count = "select count(DISTINCT(user_id)) as count from zjy_borrow_tender where user_id not in(select user_id from zjy_user where is_self=1)";
          $query = $this->db->query($sql_user_count);
          $result['tender_user_count'] = $query->row()->count; */

        return $result;
    }

    function get_user_tender_money($user_id, $start_time = 0, $end_time = 0){
    	$sql = "select sum(account) as taccount from zjy_borrow_tender where user_id=$user_id and add_time>=$start_time and add_time<$end_time and borrow_id in (select id from zjy_borrow where fstatus=3);";
        $query = $this->db->query($sql);
        $row = $query->row_array();
        return $row['taccount'];
    }

    function get_user_tender_interest($user_id, $start_time = 0, $end_time = 0){
        $sql = "select sum(interest) as tinterest from zjy_borrow_collection where user_id=$user_id and repay_yestime>=$start_time and repay_yestime<$end_time;";
        $query = $this->db->query($sql);
        $row = $query->row_array();
        return $row['tinterest'];
    }

    //增加推荐流水记录
    function insert_invite_list($data = array()){
        $this->db->insert('zjy_invite', $data);
        return $this->db->insert_id();
    }

    //获取推荐人的奖励金额
    function referee_reward($user_id){
        $sql = "select sum(yiji_reward_money) as yiji_reward_money,sum(dingji_reward_money) as dingji_reward_money from zjy_invite where user_id=$user_id;";
        $query = $this->db->query($sql);
        $row = $query->row_array();
        return $row;
    }

    //获取所推荐的人的奖励金额，一级
    function yiji_reward($user_id,$yiji_referee){
        $sql = "select sum(yiji_reward_money) as yiji_reward_money from zjy_invite where user_id=$user_id and yiji_referee=$yiji_referee;";
        $query = $this->db->query($sql);
        $row = $query->row_array();
        return $row['yiji_reward_money'];
    }

    //获取所推荐的人的奖励金额，顶级
    function dingji_reward($user_id,$dingji_referee){
        $sql = "select sum(dingji_reward_money) as dingji_reward_money from zjy_invite where user_id=$user_id and dingji_referee=$dingji_referee;";
        $query = $this->db->query($sql);
        $row = $query->row_array();
        return $row['dingji_reward_money'];
    }

    function apply_add($data){
//        $this->db->trans_start();
        if($this->db->insert('borrow_apply',$data)){
            return true;
        } else{
            return false;
        }
//        $this->db->trans_complete();
    }
}
